Build a weighted binary tree from character counts
I was asked this
No reports yet. Sign in to say where you were asked it.
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
sis a leaf exactly once. The leaf'schis the character and itscountis how many times it appears ins. -
Internal nodes. Every non-leaf node has
ch = '#', exactly two children, andcountequal 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 <= 52distinct 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
