Find Subtree Sizes After Changes - Problem
Imagine you have a family tree where each person has a unique character assigned to them. Now, here's the twist: every person wants to be closer to their ancestor who shares the same character!
You're given a tree rooted at node 0 with n nodes numbered from 0 to n-1. The tree structure is represented by a parent array where parent[i] is the parent of node i (with parent[0] = -1 since node 0 is the root). Each node i has a character s[i] assigned to it.
Here's what happens simultaneously for all nodes from 1 to n-1:
- Each node
xlooks for the closest ancestorythat has the same character (s[x] == s[y]) - If such an ancestor exists, node
xabandons its current parent and becomes a direct child of ancestory - If no such ancestor exists, the node stays put
Your task is to return an array where answer[i] represents the size of the subtree rooted at node i after all these family relocations are complete!
Input & Output
example_1.py — Basic Tree Transformation
$
Input:
parent = [-1,0,1,2], s = "abbc"
›
Output:
[4,2,1,1]
💡 Note:
Node 2 (character 'b') finds ancestor node 1 (also 'b') and becomes its child. Node 3 ('c') has no 'c' ancestors so stays under node 2. Final tree: 0->1->3, 0->2, giving sizes [4,2,1,1].
example_2.py — No Changes Needed
$
Input:
parent = [-1,0,0,1,1], s = "abcde"
›
Output:
[5,3,1,1,1]
💡 Note:
All characters are unique, so no node can find an ancestor with the same character. The tree structure remains unchanged, and subtree sizes are calculated normally.
example_3.py — Multiple Relocations
$
Input:
parent = [-1,0,1,2,3], s = "aaaaa"
›
Output:
[5,1,1,1,1]
💡 Note:
All nodes have character 'a'. Node 1 stays under root 0. Nodes 2,3,4 all move to be direct children of root 0 (closest 'a' ancestor). Final tree: 0 has children [1,2,3,4].
Constraints
- n == parent.length == s.length
- 1 ≤ n ≤ 105
- parent[0] == -1
- 0 ≤ parent[i] ≤ n - 1 for i ≠ 0
- parent represents a valid tree
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Original Structure
Start with the initial parent-child relationships
2
Find Matches
Each employee looks upward for a manager with the same specialty
3
Relocate
Employees move to report directly to their preferred manager
4
Count Teams
Calculate the size of each manager's team in the new structure
Key Takeaway
🎯 Key Insight: Using character-indexed stacks during DFS enables O(1) ancestor lookup, making the entire algorithm run in optimal O(n) time with just one tree traversal.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code