Approach
Depth-first search
For Find Subtree Sizes After Changes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 39 lines of Java from the credited upstream file 3331.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] findSubtreeSizes(int[] parent, String s) {3 final int n = parent.length;4 int[] ans = new int[n];5 int[] newParent = parent.clone();6 List<Integer>[] tree = new ArrayList[n];7 8 for (int i = 0; i < n; ++i)9 tree[i] = new ArrayList<>();10 11 for (int i = 1; i < n; ++i) {12 final int closest = findClosestAncestor(i, parent, s);13 if (closest != -1)14 newParent[i] = closest;15 }16 17 for (int i = 1; i < n; ++i)18 tree[newParent[i]].add(i);19 20 dfs(tree, 0, ans);21 return ans;22 }23 24 25 private int findClosestAncestor(int u, int[] parent, String s) {26 for (int curr = parent[u]; curr != -1; curr = parent[curr])27 if (s.charAt(curr) == s.charAt(u))28 return curr;29 return -1;30 }31 32 private int dfs(List<Integer>[] tree, int u, int[] ans) {33 int sz = 1;34 for (final int v : tree[u])35 sz += dfs(tree, v, ans);36 return ans[u] = sz;37 }38}39