Sub topic 11
Small-to-Large Merging of Subtree Sets
The earlier chapters gave each subtree a small, fixed-size state: a count, a pair of take and skip values, or a table capped at k entries. Some problems need more than that. Each subtree has to carry a whole collection, such as the set of colors that appear in it, or a map from value to how many times it appears. Combining such collections naively can cost quadratic time. Small-to-large merging keeps the total cost at O(n log n) set operations with one rule: always pour the smaller collection into the larger one.
This chapter assumes you know the root_tree helper and the reversed pre-order processing from earlier chapters. You should also know Big-O analysis and how Python sets and dictionaries behave: average O(1) insert and lookup, and a |= b costs O(len(b)).
When a Number Is Not Enough
Take this problem. Every node has a color. For every node u, report how many distinct colors appear in u's subtree.
A plain count does not combine. If child A has 3 distinct colors and child B has 4, the parent could have anywhere from 4 to 7 (plus its own color), depending on how much the two overlap. The state has to hold the actual set of colors. The transition is a set union:
S(u) = {color[u]} ∪ S(c1) ∪ S(c2) ∪ ...answer[u] = |S(u)|
The state is correct. The cost of the unions is where you can go wrong.
The Quadratic Trap
The obvious code builds a fresh set at every node:
def distinct_colors_slow(n, edges, color):
parent, order, _ = root_tree(n, edges, 0)
sets = [{color[u]} for u in range(n)]
ans = [0] * n
for u in reversed(order):
ans[u] = len(sets[u])
p = parent[u]
if p != -1:
sets[p] = sets[p] | sets[u] # builds a new set: O(|a| + |b|)
return ansRun it on a path 0 - 1 - 2 - ... - (n-1) rooted at 0, where every node has a different color. Node n-1 passes up a set of size 1. Node n-2 passes up a set of size 2, and so on. Each union copies the entire set from below, so the total work is 1 + 2 + ... + n = Θ(n²). With n = 200,000 that comes to about 2·10¹⁰ element copies, which will never finish in time.
Rewriting it as sets[p] |= sets[u] helps only by luck. On this path, sets[p] starts with one element and sets[u] holds everything below it. The in-place union iterates over the right-hand side, so you are still copying the large set into the small one, and the total is still Θ(n²).
The Rule: Pour Small Into Large
The fix is to compare sizes before every merge. If the parent's container is smaller than the child's, swap them so the parent takes over the child's container. Then insert the smaller container's elements into the larger one.
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):
parent, order, _ = root_tree(n, edges, 0)
sets = [{color[u]} for u in range(n)]
ans = [0] * n
for u in reversed(order):
# Every child of u appears later in the pre-order, so all of them
# have already been merged into sets[u]. u's set is complete.
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] # swap references, O(1)
sets[p] |= sets[u] # cost: size of the smaller set
sets[u] = None # release the small container
return ans
if __name__ == "__main__":
# 0(red)
# / \
# 1(blue) 2(red)
# / \ \
# 3(red) 4(green) 5(blue)
n = 6
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
color = ["red", "blue", "red", "red", "green", "blue"]
print(distinct_colors(n, edges, color)) # [3, 3, 2, 1, 1, 1]
path_n = 200_000
path_edges = [(i, i + 1) for i in range(path_n - 1)]
res = distinct_colors(path_n, path_edges, list(range(path_n)))
print(res[0], res[path_n - 1]) # 200000 1On the path, the swap fires at every step. The parent receives the large set by reference, and only the parent's single color gets inserted. The run that took quadratic time now finishes in linear time.
Two details decide whether this code is correct:
- Record the answer before handing the set off. After the merge,
sets[u]may beNone, or the container that used to be u's may now belong topand keep growing. A node's answer is read exactly once, at the moment its container is complete. - Swap references, never contents. The swap is two pointer assignments. Copying the large set into the parent's slot would cost exactly what the rule is meant to avoid.
Why the Total Is O(n log n)
Charge every insertion to the element being moved. When element x sits in the smaller container of a merge, it moves into a container at least as large as its old one. Its new container therefore has at least twice as many elements as its old one. A container never holds more than n elements, so x can be on the smaller side at most log₂ n times. With n elements in total, the number of insertions is at most n log₂ n. Each insertion is average O(1) for a hash set, so the whole algorithm runs in O(n log n) expected time.
This works for sets because a set of distinct colors in a subtree never has more elements than the subtree has nodes. The argument still holds when elements repeat and the merged set ends up smaller than the sum of its parts. Give each container a weight equal to the number of tree nodes it represents. The cost of a merge is min(len(A), len(B)), and since len(A) ≤ weight(A) and len(B) ≤ weight(B), that cost is at most min(weight(A), weight(B)). The doubling argument applies to node weights exactly as written above: each node is on the lighter side at most log₂ n times. Overlap can only make the real cost smaller.
Carrying Counts: Maps Instead of Sets
Many problems need multiplicities, not just membership. A classic example: for every node, find the colors that appear most often in its subtree and report the sum of those colors. Colors are integers here.
The state is a frequency map plus two summary fields: the highest frequency so far and the sum of colors that reach it. Counts in a merged map only go up, so the maximum only goes up too. That lets you update the summary incrementally during insertion, with no rescan of the large map.
class Bag:
__slots__ = ("cnt", "best", "total")
def __init__(self, c):
self.cnt = {c: 1}
self.best = 1 # highest frequency in the bag
self.total = c # sum of colors that reach that frequency
def add(self, c, k):
f = self.cnt.get(c, 0) + k
self.cnt[c] = f
if f > self.best:
self.best, self.total = f, c
elif f == self.best:
self.total += c
def dominant_color_sums(n, edges, color):
parent, order, _ = root_tree(n, edges, 0)
bags = [Bag(color[u]) for u in range(n)]
ans = [0] * n
for u in reversed(order):
ans[u] = bags[u].total
p = parent[u]
if p == -1:
continue
if len(bags[p].cnt) < len(bags[u].cnt):
bags[p], bags[u] = bags[u], bags[p]
big = bags[p]
for c, k in bags[u].cnt.items():
big.add(c, k)
bags[u] = None
return ans
def brute(n, edges, color):
parent, order, _ = root_tree(n, edges, 0)
children = [[] for _ in range(n)]
for v in range(n):
if parent[v] != -1:
children[parent[v]].append(v)
out = []
for u in range(n):
freq, stack = {}, [u]
while stack:
x = stack.pop()
freq[color[x]] = freq.get(color[x], 0) + 1
stack.extend(children[x])
m = max(freq.values())
out.append(sum(c for c, f in freq.items() if f == m))
return out
if __name__ == "__main__":
import random
for _ in range(300):
n = random.randint(1, 40)
edges = [(random.randrange(i), i) for i in range(1, n)]
color = [random.randint(1, 5) for _ in range(n)]
assert dominant_color_sums(n, edges, color) == brute(n, edges, color)
print("all random tests passed")Paste this below the first block in the same file, since it uses root_tree. The add method handles one subtle case. When a key from the small map lands on a key that already exists in the big map, the frequencies add together. The summary fields stay correct because the new frequency f is compared against best after the addition. The large bag's own entries never need to be revisited, because none of their counts changed.
Common Errors
| Mistake | Symptom | Fix | Column | Column |
|---|---|---|---|---|
| `sets[p] = sets[p] \ | sets[u]` | Θ(n²) on paths and caterpillars | Use the in-place `\ | =` after a size-based swap |
| Copying the larger container instead of swapping references | Same quadratic time, plus extra memory | Swap the two list slots | ||
| Reading `ans[u]` after merging into the parent | Answers include sibling or ancestor data, or crash on `None` | Record the answer when `u` is first visited in reversed order | ||
| Comparing sizes once per node instead of once per child | A large later child gets iterated over | Compare before every merge | ||
| Recursive DFS returning sets | `RecursionError` on deep trees | Use the iterative order from `root_tree` | ||
| Querying a child's container after it was absorbed | Silent wrong answers, because two nodes share one object | Treat a child's container as gone once merged, and answer all queries at `u` beforehand |
The last row matters for offline queries. Suppose a query asks "how many nodes of color c are in u's subtree". Group the queries by node and answer all of u's queries at the same point where ans[u] is recorded. After that point, the container belongs to an ancestor.
Choosing a Technique
Small-to-large is one of several ways to answer questions about the contents of each subtree.
| Approach | Time | Memory | Best when |
|---|---|---|---|
| Small-to-large sets or maps | O(n log n) expected | O(n) live at once | The state is a set or map and merging is a natural union |
| Keep the heavy child ("sack", DSU on tree) | O(n log n) | One global counter array | Colors fit in a small integer range, so array counters beat hash maps |
| Euler tour plus offline range queries | O(n log n) with a Fenwick tree | O(n) | The question becomes a range query over the flattened tree, such as distinct values in a range |
| Sorted containers merged small-to-large | O(n log² n) | O(n) | You need order statistics, such as the k-th smallest value in a subtree |
In Python, the plain set version is usually fastest, because |= iterates inside C code. The map version spends its time in the Python-level loop in add, so constant factors matter more there. If colors are small integers, consider the heavy-child method with a flat list of counts.
The swap is also not just an optimization. Two children with containers of n/2 each still cost n/2 to merge. That case is fine, because it can only happen at shallow levels, and the doubling argument already counts it. The swap guarantees that the larger side is never the one you iterate over.
Exercise
A tree has n nodes, and every node has a distinct color. In distinct_colors, the line if len(sets[p]) < len(sets[u]): and the swap under it are deleted, so each child's set is always iterated and inserted into the parent's set. Give a tree shape and a root where this costs Θ(n²), and a shape where it still costs O(n).
Show answer
Use a path rooted at one end, 0 - 1 - ... - (n-1) rooted at 0. Every parent starts with one element and receives a child set of size n-1-p, so the insertions total about n²/2. A star rooted at its center costs O(n): each leaf's set has size 1, so the n-1 merges insert one element each.
Exercise
Change dominant_color_sums so that each node reports the number of distinct colors that appear an odd number of times in its subtree. What extra field does Bag need, and how does add(c, k) update it?
Show answer
Store odd, the number of keys with an odd count. In add, read the old count g = cnt.get(c, 0) and set the new count f = g + k. If g is odd and f is even, decrease odd by one. If g is even and f is odd, increase it by one. A new key counts as g = 0, which is even. Every update depends only on the key being changed, so the small-to-large bound still applies.
Exercise
Explain why min(len(A), len(B)) ≤ min(weight(A), weight(B)) is enough to prove O(n log n) total insertions, even though merged sets can be much smaller than the number of nodes they represent.
Show answer
Each merge costs at most the node weight of the lighter container. Node weights add exactly when containers merge, so every node in the lighter container moves into a container at least twice its old weight. No weight can exceed n, so each node is on the lighter side at most log₂ n times. Summing over all nodes gives at most n log₂ n, and the real cost is bounded by that sum.