Ctrl K

Largest Single-Color Branch

Medium
You get a tree with n nodes numbered 0 to n - 1, rooted at node 0. The list edges holds n - 1 edges: a pair [a, b] means nodes a and b are connected. Node i is painted color colors[i]. The subtree of node v is v itself together with all of its descendants. Find a node whose entire subtree is a single color and return the largest possible size of such a subtree (its number of nodes).
Example 1
edges=[[0, 1], [1, 2], [1, 3], [0, 4]], colors=[2, 5, 5, 5, 2] → 3

The subtree of node 1 is nodes 1, 2 and 3, all of color 5: size 3. The root has children of different colors, so the whole tree does not count.

Example 2
edges=[[1, 0], [2, 0]], colors=[4, 4, 4] → 3

The whole tree is one color, so the answer is 3. Edges may be listed in either direction.

Example 3
edges=[[0, 1], [1, 2]], colors=[1, 2, 3] → 1

Only leaf 2 has a single-color subtree, consisting of just itself.

Constraints
  • 1 ≤ n = len(colors) ≤ 5·10⁴
  • len(edges) = n - 1, edges[i] = [a, b], 0 ≤ a, b < n
  • 1 ≤ colors[i] ≤ 10⁵
  • The edges form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRoute Fee Spread From the Best Start HardRoots That Fit the Guesses HardDiscounted Trips Through a Tree HardHarvesting a Tree: Toll or Half HardBiggest Search Subtree Medium
loading Python…
Input
edges=[[0, 1], [1, 2], [1, 3], [0, 4]], colors=[2, 5, 5, 5, 2]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 66 tests on the server, hidden ones included.