Maximum Subtree of the Same Color - Problem

You're given a tree with n nodes numbered from 0 to n-1, rooted at node 0. The tree structure is defined by a 2D array edges where edges[i] = [ui, vi] represents an edge between nodes ui and vi.

Each node is painted with a color represented by the array colors, where colors[i] is the color of node i.

Your goal is to find the largest subtree where all nodes have the same color. A subtree rooted at node v includes node v and all its descendants.

Return the maximum number of nodes in such a monochromatic subtree.

Example: If we have a tree where node 2 and all its children have color 'red', and this subtree contains 5 nodes, while no other subtree has more than 5 nodes of the same color, then the answer is 5.

Input & Output

example_1.py โ€” Basic Tree
$ Input: edges = [[0,1],[0,2],[2,3],[2,4]], colors = [1,2,2,2,2]
โ€บ Output: 3
๐Ÿ’ก Note: The subtree rooted at node 2 contains nodes {2,3,4} all with color 2, giving us the maximum size of 3.
example_2.py โ€” Single Node
$ Input: edges = [], colors = [1]
โ€บ Output: 1
๐Ÿ’ก Note: With only one node, the maximum monochromatic subtree has size 1.
example_3.py โ€” All Different Colors
$ Input: edges = [[0,1],[1,2],[2,3]], colors = [1,2,3,4]
โ€บ Output: 1
๐Ÿ’ก Note: Every node has a different color, so the maximum monochromatic subtree size is 1 (any single node).

Constraints

  • 1 โ‰ค n โ‰ค 105
  • edges.length == n - 1
  • 0 โ‰ค ui, vi < n
  • 1 โ‰ค colors[i] โ‰ค 105
  • The input represents a valid tree (connected and acyclic)

Visualization

Tap to expand
0Red1Blue2Blue3Blue4BlueMonochromaticSubtreeSize: 3 nodesโ‘  Process leaves firstโ‘ก Then parent nodesFinal ResultMaximum Size: 3Subtree: {2, 3, 4}
Understanding the Visualization
1
Build Tree Structure
Convert edge list to adjacency list representation
2
Start DFS from Root
Begin post-order traversal from node 0
3
Process Leaf Nodes
Leaf nodes are always monochromatic (size 1)
4
Check Parent Nodes
For each parent, verify if all children have the same color
5
Calculate Subtree Sizes
If monochromatic, sum up all children sizes + 1
6
Track Maximum
Keep track of the largest monochromatic subtree found
Key Takeaway
๐ŸŽฏ Key Insight: Post-order DFS allows us to solve this efficiently in O(n) time by processing children before parents and building up subtree information bottom-up.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
42.3K Views
Medium-High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen