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.

Google
Coding & Algorithms
Frontend Engineer
Google
November 29, 2026
Frontend Engineer
Onsite
Coding & Algorithms
Medium

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
binary trees
hashing
serialization
post-order traversal
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported