Graph Theory37 sections · 1633 units
Open in Course

Distinct Colors - Naive Approach

(Why it times out)

For each node, run a DFS to collect all colors in its subtree, then count distinct values. This is O(n)O(n) per node, so O(n2)O(n^2) total. Too slow. Alternatively, maintain a set per node and merge child sets after processing them. If you merge in arbitrary order, you hit the O(n2)O(n^2) chain case.

Small-to-large merging fixes this. By always merging the smaller set into the larger one, you guarantee O(nlogn)O(n \log n) total operations across all merges in the tree.