Find Repeated Subtrees in a Large UI Component Tree
Last updated: November 29, 2026
Quick Overview
Given a binary tree of UI components, return one representative root for each subtree shape-and-value pattern that occurs two or more times.
0
0
0 solved
Given a binary tree of UI components, return one representative root for each subtree shape-and-value pattern that occurs two or more times.
A Google onsite problem about deduplicating repeated component subtrees for caching. String serialization works but is O(n^2) in memory; the interviewer is looking for assigning integer IDs to subtree signatures for O(n).
What the Interviewer Expects
- Serialize each subtree with explicit null markers
- Use a hash map to count occurrences
- Report each repeated pattern exactly once
- Replace strings with integer IDs of (val, leftId, rightId) for O(n)
- Explain why null markers are necessary
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Why is plain string serialization O(n^2) on a skewed tree?
- Return the count of distinct subtree patterns.
- Find the largest repeated subtree.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: root. Output: list of nodes, one per pattern seen at least twice, in any order. Two subtrees match when they have the same shape and the same values at each position....
High-Level Design
Post-order traversal gives each subtree a canonical identity built from its children's identities. Concatenating serialized strings works but each string can be O(n) long, so total cost is O(n^2) on a...