KatInterview

Build Frequency-Based Binary Codec

Trees & GraphsAuto-graded · 24 test cases
HardAuto-gradedTrees & Graphstreesheapsgreedy

Last 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:

  1. Count frequencies: Determine how many times each character appears.

  2. Initialize leaf nodes: Create one node for each unique character, with its frequency as the node's weight.

  3. 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).
  4. 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
  5. Encode the string: Replace each character in s with 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_character is the character itself.
  • For an internal node, minimum_character is 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 (assigned 0).

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 on 1.
  • 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.