/**
* Problem: LeetCode 3331 - Find Subtree Sizes After Changes
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.Arrays;
class Solution {
public int[] findSubtreeSizes(int[] parent, String s) {
int n = parent.length;
// Children ki adjacency list (linked-list style)
int[] head = new int[n];
int[] nxt = new int[n];
Arrays.fill(head, -1);
for (int i = 1; i < n; i++) {
nxt[i] = head[parent[i]];
head[parent[i]] = i;
}
int[] last = new int[26]; // last[c] = current path pe c character wala sabse nazdeeki ancestor
Arrays.fill(last, -1);
int[] newPar = parent.clone(); // changes ke baad parent
int[] saved = new int[n]; // backtrack ke liye purani last[] value
int[] order = new int[n]; // DFS preorder
int cnt = 0;
int[] it = head.clone(); // har node ka next child pointer
int[] stack = new int[n];
int sp = 0;
// Root enter karo
int c0 = s.charAt(0) - 'a';
saved[0] = last[c0];
last[c0] = 0;
order[cnt++] = 0;
stack[sp++] = 0;
// Iterative DFS (n = 10^5 pe recursion se stack overflow ho sakta hai)
while (sp > 0) {
int x = stack[sp - 1];
if (it[x] != -1) {
int child = it[x];
it[x] = nxt[child];
int c = s.charAt(child) - 'a';
saved[child] = last[c];
if (last[c] != -1) newPar[child] = last[c]; // closest same-char ancestor mila
last[c] = child;
order[cnt++] = child;
stack[sp++] = child;
} else {
sp--;
last[s.charAt(x) - 'a'] = saved[x]; // backtrack
}
}
// Subtree sizes: preorder ko reverse mein process karo (child pehle, parent baad mein)
int[] size = new int[n];
Arrays.fill(size, 1);
for (int i = n - 1; i >= 1; i--) {
int x = order[i];
size[newPar[x]] += size[x];
}
return size;
}
}
"""
Problem: LeetCode 3331 - Find Subtree Sizes After Changes
Difficulty: Medium
Language: Python 3
Author: CodeByTushu
"""
from typing import List
class Solution:
def findSubtreeSizes(self, parent: List[int], s: str) -> List[int]:
n = len(parent)
children = [[] for _ in range(n)]
for i in range(1, n):
children[parent[i]].append(i)
new_parent = list(parent)
last = [-1] * 26
order = []
# Iterative DFS to prevent recursion depth exceeded on deep trees (n <= 10^5)
stack = [0]
child_idx = [0] * n
saved = [-1] * n
c0 = ord(s[0]) - ord('a')
saved[0] = last[c0]
last[c0] = 0
order.append(0)
while stack:
u = stack[-1]
if child_idx[u] < len(children[u]):
v = children[u][child_idx[u]]
child_idx[u] += 1
c = ord(s[v]) - ord('a')
saved[v] = last[c]
if last[c] != -1:
new_parent[v] = last[c]
last[c] = v
order.append(v)
stack.append(v)
else:
stack.pop()
last[ord(s[u]) - ord('a')] = saved[u]
# Reverse preorder traversal to calculate subtree sizes from leaves to root
size = [1] * n
for i in range(n - 1, 0, -1):
x = order[i]
size[new_parent[x]] += size[x]
return size
/**
* Problem: LeetCode 3331 - Find Subtree Sizes After Changes
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<int> findSubtreeSizes(vector<int>& parent, string s) {
int n = parent.size();
vector<vector<int>> children(n);
for (int i = 1; i < n; i++) {
children[parent[i]].push_back(i);
}
vector<int> newPar = parent;
vector<int> last(26, -1);
vector<int> saved(n, -1);
vector<int> order;
order.reserve(n);
vector<int> it(n, 0);
vector<int> stack;
stack.reserve(n);
int c0 = s[0] - 'a';
saved[0] = last[c0];
last[c0] = 0;
order.push_back(0);
stack.push_back(0);
// Iterative DFS
while (!stack.empty()) {
int x = stack.back();
if (it[x] < (int)children[x].size()) {
int child = children[x][it[x]++];
int c = s[child] - 'a';
saved[child] = last[c];
if (last[c] != -1) newPar[child] = last[c];
last[c] = child;
order.push_back(child);
stack.push_back(child);
} else {
stack.pop();
last[s[x] - 'a'] = saved[x];
}
}
// Subtree sizes using reverse preorder traversal
vector<int> size(n, 1);
for (int i = n - 1; i >= 1; i--) {
int x = order[i];
size[newPar[x]] += size[x];
}
return size;
}
};
/**
* Problem: LeetCode 3331 - Find Subtree Sizes After Changes
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} parent
* @param {string} s
* @return {number[]}
*/
var findSubtreeSizes = function(parent, s) {
const n = parent.length;
const head = new Int32Array(n).fill(-1);
const nxt = new Int32Array(n).fill(-1);
for (let i = 1; i < n; i++) {
nxt[i] = head[parent[i]];
head[parent[i]] = i;
}
const last = new Int32Array(26).fill(-1);
const newPar = new Int32Array(parent);
const saved = new Int32Array(n).fill(-1);
const order = new Int32Array(n);
let cnt = 0;
const it = new Int32Array(head);
const stack = new Int32Array(n);
let sp = 0;
const c0 = s.charCodeAt(0) - 97;
saved[0] = last[c0];
last[c0] = 0;
order[cnt++] = 0;
stack[sp++] = 0;
while (sp > 0) {
const x = stack[sp - 1];
if (it[x] !== -1) {
const child = it[x];
it[x] = nxt[child];
const c = s.charCodeAt(child) - 97;
saved[child] = last[c];
if (last[c] !== -1) newPar[child] = last[c];
last[c] = child;
order[cnt++] = child;
stack[sp++] = child;
} else {
sp--;
last[s.charCodeAt(x) - 97] = saved[x];
}
}
const size = new Int32Array(n).fill(1);
for (let i = n - 1; i >= 1; i--) {
const x = order[i];
size[newPar[x]] += size[x];
}
return Array.from(size);
};
TIME COMPLEXITY
O(n)
SPACE COMPLEXITY
O(n)
TOPICS
Binary Tree
DFS
Dynamic Programming
Tree
Tree / Binary Tree