Build Frequency-Based Binary Codec
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests ability to construct a deterministic frequency tree with tie-breaking, generate prefix-free binary codes, and encode/decode strings.
Problem
Create a binary compression and decompression system that assigns shorter codes to more frequent characters.
Implement a function that takes a string and returns a three-element list: the encoded bitstring, the encoding tree, and the decoded result (which should match the input).
Encoding Algorithm
Given an input string s:
-
Count frequencies: Determine how many times each character appears.
-
Initialize leaf nodes: Create one node for each unique character, with its frequency as the node's weight.
-
Build the tree: Repeatedly merge the two lightest nodes:
- Remove the two nodes with smallest weights from the pool.
- Create a new parent node with weight equal to the sum of its children's weights.
- Make the two removed nodes the left and right children of this parent.
- Add the parent back to the pool.
- Continue until only one node remains (the root).
-
Assign binary codes: Each character's code is the sequence of left/right decisions from root to that character's leaf:
- Left edge =
0 - Right edge =
1
- Left edge =
-
Encode the string: Replace each character in
swith its binary code and concatenate.
Tie-Breaking Rules
When multiple nodes have the same weight, use this deterministic ordering:
- Compare nodes by
(weight, minimum_character). - For a leaf node,
minimum_characteris the character itself. - For an internal node,
minimum_characteris the lexicographically smallest character among all leaves in its subtree. - When attaching children to a parent, the node with smaller
(weight, minimum_character)becomes the left child (assigned0).
Tree Representation
Represent each node as a dictionary:
{
"char": "a" or None, # character for leaves, None for internal nodes
"left": node or None, # left child
"right": node or None # right child
}
Decoding
To decode, traverse the tree following the bits:
- Start at the root.
- For each bit: go left on
0, right on1. - When reaching a leaf, output its character and return to the root.
Special Cases
- Empty string: Return
["", None, ""]. - Single unique character (e.g.,
"aaaa"): The tree is a single leaf with no children. Assign the code"0"to that character.
Constraints
0 ≤ len(s) ≤ 200,000- String contains ASCII characters only
- At most 256 distinct characters
- Target complexity: O(n + k log k) time where n = string length, k = number of distinct characters
Examples
Example 1
Input: build_frequency_codec('')
Output: ['', None, '']
Example 2
Input: build_frequency_codec('aaaa')
Output: ['0000', {'char': 'a', 'left': None, 'right': None}, 'aaaa']
Example 3
Input: build_frequency_codec('abacaba')
Output: ['1011001011', {'char': None, 'left': {'char': None, 'left': {'char': 'c', 'left': None, 'right': None}, 'right': {'char': 'b', 'left': None, 'right': None}}, 'right': {'char': 'a', 'left': None, 'right': None}}, 'abacaba']
Example 4
Input: build_frequency_codec('hello world')
Output: ['11111110101000110001100010101101', {'char': None, 'left': {'char': None, 'left': {'char': 'o', 'left': None, 'right': None}, 'right': {'char': None, 'left': {'char': 'r', 'left': None, 'right': None}, 'right': {'char': 'w', 'left': None, 'right': None}}}, 'right': {'char': None, 'left': {'char': 'l', 'left': None, 'right': None}, 'right': {'char': None, 'left': {'char': None, 'left': {'char': ' ', 'left': None, 'right': None}, 'right': {'char': 'd', 'left': None, 'right': None}}, 'right': {'char': None, 'left': {'char': 'e', 'left': None, 'right': None}, 'right': {'char': 'h', 'left': None, 'right': None}}}}}, 'hello world']
Hints
Hint 1
Use a min-heap to efficiently find and merge the two lightest nodes repeatedly.
Hint 2
Store the minimum character in each internal node during construction to enable deterministic tie-breaking.
Hint 3
For a single-character string, create a leaf-only tree and use '0' as the code to avoid an empty code path.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building a prefix-free binary encoding scheme where more frequent characters receive shorter codes.
Step 1: Build the frequency tree
Start by counting how often each character appears. Create a min-heap where each entry is a tuple (weight, min_char, sequence, node). The min_char field stores the lexicographically smallest character in that subtree, enabling deterministic tie-breaking when weights are equal.
Repeatedly extract the two entries with smallest (weight, min_char) tuples. The first extracted node (with smaller comparison value) becomes the left child and gets edge label 0. Create a parent node with combined weight and the minimum of the two min_char values, then push it back into the heap. Continue until one node remains.
Step 2: Generate character codes
Traverse the tree from root to each leaf, accumulating the path of 0s and 1s. Store these codes in a lookup table mapping each character to its binary string.
Step 3: Encode
Walk through the input string and replace each character with its code from the lookup table. Concatenate all codes into a single bitstring.
Step 4: Decode
Start at the tree root. For each bit in the encoded string, move left on 0 or right on 1. When reaching a leaf, output its character and jump back to the root. Continue until all bits are consumed.
Why this works
The tie-breaking rule ensures that when weights are equal, the node containing the lexicographically smallest character is always chosen first and placed left. This makes the tree construction completely deterministic. Since characters only appear at leaves, no code can be a prefix of another, making decoding unambiguous.
Edge cases
For an empty string, return empty results. For a string with only one distinct character, the tree is a single leaf with no edges. Assign it the code "0" so that encoding produces a string of 0s equal in length to the input.
Complexity
- Time: O(n) for counting frequencies, O(k log k) for k−1 heap merges, O(k) for code generation, O(n) for encoding, O(encoded length) for decoding. Total: O(n + k log k).
- Space: O(k) for the tree and code table, plus O(encoded length) for output.
Where n is the input string length and k is the number of distinct characters (at most 256).
import heapq
from typing import List
def build_frequency_codec(s: str) -> List[object]:
if not s:
return ["", None, ""]
# Count character frequencies
freq_map = {}
for char in s:
freq_map[char] = freq_map.get(char, 0) + 1
# Build initial heap with leaf nodes
heap = []
counter = 0
for char in sorted(freq_map):
node = {"char": char, "left": None, "right": None}
heapq.heappush(heap, (freq_map[char], char, counter, node))
counter += 1
# Handle single character case
if len(heap) == 1:
tree = heap[0][3]
code_table = {tree["char"]: "0"}
else:
# Build tree by merging nodes
while len(heap) > 1:
weight1, key1, _, node1 = heapq.heappop(heap)
weight2, key2, _, node2 = heapq.heappop(heap)
# Ensure smaller (weight, key) goes left
if (weight2, key2) < (weight1, key1):
weight1, key1, node1, weight2, key2, node2 = weight2, key2, node2, weight1, key1, node1
parent = {"char": None, "left": node1, "right": node2}
parent_key = min(key1, key2)
heapq.heappush(heap, (weight1 + weight2, parent_key, counter, parent))
counter += 1
tree = heap[0][3]
code_table = {}
# Generate codes by traversing tree
def build_codes(node, code):
if node["char"] is not None:
code_table[node["char"]] = code
return
build_codes(node["left"], code + "0")
build_codes(node["right"], code + "1")
build_codes(tree, "")
# Encode the string
encoded = "".join(code_table[char] for char in s)
# Decode to verify
result = []
current = tree
if tree["left"] is None and tree["right"] is None:
# Single character tree
result = [tree["char"]] * len(encoded)
else:
for bit in encoded:
current = current["left"] if bit == "0" else current["right"]
if current["char"] is not None:
result.append(current["char"])
current = tree
return [encoded, tree, "".join(result)]