← Questions

Build a weighted binary tree from character counts

0
GoogleCodingLast asked Jun 2026

A coding interview question asked in Google's onsite coding round, last asked Jun 2026. It tests trees, heap and greedy.

Given a string s of letters ('A'-'Z', 'a'-'z'; case matters), build a binary tree that summarizes how often each character appears.

Each node has three fields: ch, count, and two child pointers.

Rules for a valid tree

  • Leaves. Every distinct character of s is a leaf exactly once. The leaf's ch is the character and its count is how many times it appears in s.
  • Internal nodes. Every non-leaf node has ch = '#', exactly two children, and count equal to the sum of the counts of all leaves under it.

Goal. Among all valid trees, return one with the smallest total weighted depth:

cost = sum over leaves of (leaf.count * depth(leaf))   # the root has depth 0

so characters that occur often sit close to the root.

Implement:

def build_tree(s: str) -> Node | None

Return None for an empty string. If s has one distinct character, the root is that leaf.

Constraints: 0 <= len(s) <= 10^6. Any optimal tree is accepted when counts tie.

Example 1

s = "mmmmmmxxyz" -> counts m:6, x:2, y:1, z:1.

One optimal tree:

          #(10)
         /     \
      m(6)     #(4)
              /    \
           x(2)    #(2)
                  /    \
               y(1)    z(1)

Cost = 6*1 + 2*2 + 1*3 + 1*3 = 16.

Example 2

s = "pqrs" -> all counts are 1. A balanced tree puts every leaf at depth 2, cost 8. A chain such as p at depth 1, q at depth 2, r and s at depth 3 is valid but costs 9, so it is not accepted.

Possible follow-ups: produce a bit code per character and decode a bit string with the tree; serialize the tree; build in O(k) when the counts arrive sorted.

Clarifying questions

  • Are only letters allowed, or should other characters raise an error?
  • For a single distinct character, the root is the leaf at depth 0, so the cost is 0. Is that right?
  • When counts tie, does the shape need to be deterministic, or is any optimal tree fine?
  • Should the function also return the cost, or just the tree?

What a strong answer covers

  • Counts characters, then builds the tree the Huffman way: put every leaf in a min-heap by count, repeatedly pop the two smallest, join them under a '#' node with the summed count, and push it back until one node is left.
  • Explains why it is optimal: the two least frequent characters can always be siblings at the deepest level of some optimal tree, and merging them leaves the same problem one size smaller.
  • Adds a tie-breaker (such as an insertion counter) to the heap entries so nodes are never compared directly.
  • O(n) to count and O(k log k) for the heap, with k <= 52 distinct characters. Handles the empty string and a single distinct character.
  • Tests: both examples, checking the cost rather than the exact shape, a string of one repeated letter, upper and lower case as different characters, and a check of every internal node's count.

Follow-ups

  • Produce a bit code for each character and decode a bit string with the tree.
  • Serialize the tree so a decoder can rebuild it.
  • Build the tree in O(k) when the counts arrive sorted, with two queues.
  • Limit the depth of the tree to L (length-limited codes).

Where it's asked

  • Google · Onsite coding · Last asked Jun 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

trees · heap · greedy · huffman

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding