Maximum Subtree of the Same Color - Problem

You are given a 2D integer array edges representing a tree with n nodes, numbered from 0 to n - 1, rooted at node 0, where edges[i] = [ui, vi] means there is an edge between the nodes vi and ui.

You are also given a 0-indexed integer array colors of size n, where colors[i] is the color assigned to node i.

We want to find a node v such that every node in the subtree of v has the same color. Return the size of such subtree with the maximum number of nodes possible.

Input & Output

Example 1 — Basic Tree
$ Input: edges = [[0,1],[1,2],[2,3],[3,4]], colors = [1,1,2,1,1]
Output: 2
💡 Note: Node 1 has a subtree containing nodes {1, 4} both with color 1. This is the largest same-color subtree with size 2.
Example 2 — All Same Color
$ Input: edges = [[0,1],[0,2]], colors = [1,1,1]
Output: 3
💡 Note: All nodes have color 1, so the entire tree starting from node 0 forms a same-color subtree of size 3.
Example 3 — No Large Subtrees
$ Input: edges = [[0,1],[0,2]], colors = [1,2,3]
Output: 1
💡 Note: Each node has a different color, so the maximum same-color subtree size is 1 (any single node).

Constraints

  • 2 ≤ edges.length ≤ 105
  • 0 ≤ edges[i][0], edges[i][1] < n
  • 1 ≤ colors[i] ≤ 105

Visualization

Tap to expand
Maximum Subtree of the Same Color INPUT Tree Structure (rooted at 0) 0 c=1 1 c=1 2 c=2 3 c=1 4 c=1 colors=[1,1,2,1,1] ALGORITHM STEPS 1 Build Adjacency List Create tree from edges 2 DFS from Root Post-order traversal 3 Check Subtree Colors Return size if uniform 4 Track Maximum Update max size found DFS Results Table Node Size Uniform? Max 4 1 OK 1 3 2 OK 2 2 3 NO 2 1 4 NO 2 0 5 NO 2 FINAL RESULT Maximum Uniform Subtree Subtree at Node 3 3 c=1 4 c=1 Size = 2 nodes Output 2 Both nodes have color = 1 Key Insight: Use post-order DFS: process children first, then check if current node's subtree is uniform. A subtree is uniform only if ALL children's subtrees are uniform AND have the same color as parent. Node 2 (color=2) breaks uniformity, so max uniform subtree is rooted at node 3 with size 2. TutorialsPoint - Maximum Subtree of the Same Color | Optimized DFS - Single Traversal
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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