- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 45 lines of Java from the credited upstream file 834.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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[] sumOfDistancesInTree(int n, int[][] edges) {3 int[] ans = new int[n];4 int[] count = new int[n];5 Set<Integer>[] tree = new Set[n];6 7 Arrays.fill(count, 1);8 9 for (int i = 0; i < n; ++i)10 tree[i] = new HashSet<>();11 12 for (int[] edge : edges) {13 final int u = edge[0];14 final int v = edge[1];15 tree[u].add(v);16 tree[v].add(u);17 }18 19 postorder(tree, 0, -1, count, ans);20 preorder(tree, 0, -1, count, ans);21 return ans;22 }23 24 private void postorder(Set<Integer>[] tree, int u, int prev, int[] count, int[] ans) {25 for (final int v : tree[u]) {26 if (v == prev)27 continue;28 postorder(tree, v, u, count, ans);29 count[u] += count[v];30 ans[u] += ans[v] + count[v];31 }32 }33 34 private void preorder(Set<Integer>[] tree, int u, int prev, int[] count, int[] ans) {35 for (final int v : tree[u]) {36 if (v == prev)37 continue;38 39 40 ans[v] = ans[u] - count[v] + (tree.length - count[v]);41 preorder(tree, v, u, count, ans);42 }43 }44}45