1110. Colours in Every Subtree
A festival hangs n lanterns from a rope network shaped like a tree. The lanterns are numbered 0 to n - 1, lantern 0 is the one fixed to the ceiling (the root), and each entry [a, b] of edges is a rope joining lanterns a and b. Lantern i glows with colour colours[i], and different numbers mean different colours.
The subtree of a lantern consists of the lantern itself and every lantern hanging below it, that is, every lantern whose route to the root passes through it. Return an array answer of length n where answer[i] is the number of distinct colours that appear in the subtree of lantern i.
Example 1
- Input:
- n = 7edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]colours = [5,3,5,3,8,8,5]
- Output:
- [3,2,2,1,1,1,1]
- Explanation:
Lantern 1's subtree shows colours 3 and 8, lantern 2's shows 5 and 8, and the root sees 3, 5 and 8, so colour 8 (present on both sides) is counted once.
Example 2
- Input:
- n = 4, edges = [[0,1],[1,2],[2,3]], colours = [9,9,9,9]
- Output:
- [1,1,1,1]
- Explanation:
Every lantern in this hanging chain has the same colour, so each subtree shows exactly 1 colour.
Example 3
- Input:
- n = 5edges = [[2,0],[2,1],[2,3],[2,4]]colours = [4,1,2,3,4]
- Output:
- [4,1,4,1,1]
- Explanation:
Lantern 2 hangs below the root and has three lanterns under it; lantern 4 repeats the root's colour 4, so the root and lantern 2 both see 4 distinct colours.
Constraints
1 ≤ n ≤ 100000
edges.length == n - 1; the ropes form a tree and 0 ≤ a, b < n
0 ≤ colours[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)