Graph Theory37 sections · 1633 units
Open in Course

Reveal - Lomsat gelral

(Why Small-to-Large works)

For each node, you need to merge frequency maps from all its children. If you merge naively, you recompute everything from scratch, giving O(n2)O(n^2) time. Small-to-Large merging fixes this. For each node, keep the largest child's frequency map.

Then merge all smaller children into it, one color at a time. Each color gets moved at most O(logn)O(\log n) times (it only moves when its subtree is the smaller one). Total: O(nlogn)O(n \log n).

Space complexity is O(n)O(n) for the data structures used.