Graph Theory37 sections · 1633 units
Open in Course

Distinct Colors - Algorithm

(Small-to-large merging)

First pass: compute subtree sizes using a simple DFS. Store size[v] for every node. Second pass: for each node vv, process all children recursively. Identify the child with the largest subtree. Take that child's color set as the base.

Merge all other children's sets into it by inserting their elements. Add vv's own color to the set. Count distinct colors using set.size()set.size(). Store this count as the answer for vv. Repeat for all nodes.

This runs in O(nlogn)O(n \log n) time and uses O(n)O(n) space.