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
Understanding the Visualization
1
Input Tree
Tree with colored nodes represented by edges and colors arrays
2
Find Subtrees
Check each possible subtree for uniform color
3
Maximum Size
Return the size of largest same-color subtree
Key Takeaway
🎯 Key Insight: Use DFS to explore all possible subtrees and find the largest one with uniform node colors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code