Sub topic 11
Small-to-Large Merging of Subtree Sets
This chapter assumes you know the root_tree helper from earlier chapters, the reversed pre-order trick for processing children before parents, and how Python sets and dicts behave, including their average O(1) insert and lookup.
In most earlier chapters, each subtree passed its parent a few numbers or a table capped at size k. Some problems need much more than that. A query like "how many distinct colors appear in each subtree?" requires each subtree to know exactly which colors it contains, and that set can be as large as the subtree itself. Small-to-large merging keeps the cost of combining these sets low.
The naive merge and why it fails
The obvious approach builds a fresh set at every node by copying in all of its children's sets. On a path of n nodes, node i copies a set of size n − i. The total work is 1 + 2 + … + n, which is O(n²). For n = 200,000 that is about 2·10¹⁰ operations.
The fix has two parts:
- Never copy the bigger set. Reuse it as the parent's container.
- Insert the elements of the smaller set into the bigger one.
Why each element moves only O(log n) times
Consider one element and count how many times it is inserted. An element is only moved when it sits in the smaller of the two sets being merged, so the set it lands in is at least twice the size of the set it left. A set can never hold more than n elements, so the size can double at most log₂ n times. Each element therefore moves at most log₂ n times. With n elements in total, the whole algorithm does O(n log n) set insertions.
| Strategy | Work on a path | Work in general |
|---|---|---|
| Copy all children into a new set | O(n²) | O(n²) |
| Small-to-large with reference swap | O(n log n) | O(n log n) |
Distinct colors in every subtree
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
def distinct_colors(n, edges, color, root=0):
parent, order, _ = root_tree(n, edges, root)
sets = [{color[u]} for u in range(n)]
ans = [0] * n
for u in reversed(order):
# All children of u were merged into sets[u] already.
ans[u] = len(sets[u])
p = parent[u]
if p == -1:
continue
if len(sets[p]) < len(sets[u]):
sets[p], sets[u] = sets[u], sets[p]
sets[p].update(sets[u]) # cost: size of the smaller set
sets[u] = None
edges = [(0, 1), (0, 2), (1, 3), (1, 4)]
color = [1, 2, 1, 2, 3]
print(distinct_colors(5, edges, color)) # [3, 2, 1, 1, 1]When node u comes up in the reversed order, all of its children have already been folded into sets[u], so its answer is final. The node records the answer and then hands its set up to the parent. The swap exchanges two references, which costs O(1), and update costs time proportional to the smaller set.
Common errors
- Copying instead of swapping. Writing
sets[p] = sets[u] | sets[p]builds a new set the size of both inputs, which brings back O(n²) behavior. Use the reference swap followed byupdate. - Comparing the wrong sizes. Compare the current lengths of the containers, not the subtree sizes from
root_tree. For a set of colors, the container can be much smaller than the subtree. - Using recursion. A recursive version fails on deep paths because Python's default recursion limit is 1000. The reversed-order loop has no depth limit.
Variations
The same pattern works for dictionaries. To find the most frequent color in each subtree, store color -> count per node and add the smaller map's counts into the larger one. Track the best count as you go, because the larger map's best can only improve when counts are added. Mergeable structures such as sorted containers or heaps work the same way, but each insertion then costs O(log n), so the total becomes O(n log² n).
A related technique called DSU on tree (also known as "sack") keeps the container from each node's heaviest child, meaning the child with the largest subtree, and re-inserts the lighter children's elements. It has the same O(n log n) bound, and it helps when a node's data has to be built from its subtree's raw elements rather than from the children's sets.
Exercise
A tree with n nodes is a single path, and every node has a different color. How many total insertions does distinct_colors perform, and how many would the naive copy-everything approach perform?
Show answer
At each step the parent holds a set of size 1 and the child holds the larger set, so the references are swapped and exactly one element is inserted. That gives n − 1 insertions in total, which is O(n). The naive approach copies sets of sizes 1, 2, …, n − 1, which is about n²/2 insertions.
Exercise
Why does the bound fail if, instead of comparing lengths, you always merge the child's set into the parent's set?
Show answer
An element in a large child set can then be moved into a parent set that is much smaller, so the destination no longer doubles in size. On a path, the whole accumulated set gets moved at every step, which gives O(n²) insertions.