Intuition
During one depth-first walk, keep a stack of on-path ancestors for each letter; the top of a node's letter stack is the closest same-letter ancestor, which becomes its new parent.
Explanation
Key idea
Every node x either stays put or is re-attached to the closest ancestor y on the path from the root with s[y] == s[x]. Nothing ever moves sideways or down. A node only moves up to a same-letter ancestor. So if we learn each node's new parent, the final tree is fully determined. Because every new parent is an ancestor, the result is still a tree whose sizes we can add up from the bottom.
Finding the new parents in one DFS
The "closest same-letter ancestor" is a per-path, per-letter question. Keep 26 stacks, one per letter. Each stack holds the nodes currently on the path from the root to the node we are visiting, in depth order.
When we step onto node x:
- The top of the stack for letter
s[x]is the deepest ancestor on the path that sharesx's letter, and that is its new parent. If that stack is empty, no such ancestor exists, soxkeeps its original parent. - Then push
xonto its own letter's stack and recurse into its children. - When we leave
x, pop it back off so it no longer counts for siblings elsewhere.
Accumulating sizes
Build the children lists of the final tree from the new parents, then add each node's size into its parent from the leaves upward. Because a new parent is always an ancestor, processing nodes after their descendants is enough.
Worked example
parent = [-1,0,0,1,1,1], s = "abaabc" (node → letter: 0→a, 1→b, 2→a, 3→a, 4→b, 5→c).
- Enter 0 (
a), pusha: [0]. - Enter 1 (
b): stackbempty → parent stays 0. Pushb: [1].- Enter 3 (
a): stackatop is 0 → new parent is 0 (it was 1). Push/popa. - Enter 4 (
b): stackbtop is 1 → new parent 1 (unchanged). - Enter 5 (
c): stackcempty → parent stays 1.
- Enter 3 (
- Enter 2 (
a): stackatop is 0 → parent stays 0.
New parents: node 3 moves from 1 to 0; everyone else is unchanged. Final children: 0 → {1, 2, 3}, 1 → {4, 5}. Sizes from the bottom: leaves 2,3,4,5 are 1; node 1 = 1 + 4 + 5 = 3; node 0 = 1 + (2) + (3) + subtree(1)=3 → 6. Answer [6,3,1,1,1,1].
Complexity
- Time: O(n). Each node is pushed and popped once, and sizes are summed once.
- Space: O(n). The children lists, the stacks, and the recursion/explicit stack.
Implementation
class Solution {
public int[] findSubtreeSizes(int[] parent, String s) {
int n = parent.length;
List<List<Integer>> children = new ArrayList<>();
for (int i = 0; i < n; i++) children.add(new ArrayList<>());
for (int i = 1; i < n; i++) children.get(parent[i]).add(i);
// For each node find its new parent: the closest ancestor on the current
// path with the same character. One iterative DFS, keeping a per-letter
// stack of ancestors currently on the root-to-node path.
int[] newParent = new int[n];
newParent[0] = -1;
Deque<Integer>[] stacks = new ArrayDeque[26];
for (int i = 0; i < 26; i++) stacks[i] = new ArrayDeque<>();
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{0, 0});
while (!stack.isEmpty()) {
int[] frame = stack.pop();
int node = frame[0];
int c = s.charAt(node) - 'a';
if (frame[1] == 1) {
stacks[c].pop();
continue;
}
if (node != 0) {
newParent[node] = stacks[c].isEmpty() ? parent[node] : stacks[c].peek();
}
stacks[c].push(node);
stack.push(new int[]{node, 1});
for (int child : children.get(node)) stack.push(new int[]{child, 0});
}
// Subtree sizes in the final tree; every new parent is an ancestor.
List<List<Integer>> finalChildren = new ArrayList<>();
for (int i = 0; i < n; i++) finalChildren.add(new ArrayList<>());
for (int i = 1; i < n; i++) finalChildren.get(newParent[i]).add(i);
List<Integer> order = new ArrayList<>();
Deque<Integer> st = new ArrayDeque<>();
st.push(0);
while (!st.isEmpty()) {
int u = st.pop();
order.add(u);
for (int v : finalChildren.get(u)) st.push(v);
}
int[] size = new int[n];
Arrays.fill(size, 1);
for (int idx = order.size() - 1; idx >= 0; idx--) {
int u = order.get(idx);
if (newParent[u] != -1) size[newParent[u]] += size[u];
}
return size;
}
}