- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 45 lines of Java from the credited upstream file 2277.java.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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[] closestNode(int n, int[][] edges, int[][] query) {3 int[] ans = new int[query.length];4 List<Integer>[] tree = new List[n];5 int[][] dist = new int[n][n];6 Arrays.stream(dist).forEach(A -> Arrays.fill(A, -1));7 8 for (int i = 0; i < n; ++i)9 tree[i] = new ArrayList<>();10 11 for (int[] edge : edges) {12 final int u = edge[0];13 final int v = edge[1];14 tree[u].add(v);15 tree[v].add(u);16 }17 18 for (int i = 0; i < n; ++i)19 fillDist(tree, i, i, 0, dist);20 21 for (int i = 0; i < query.length; ++i) {22 final int start = query[i][0];23 final int end = query[i][1];24 final int node = query[i][2];25 ans[i] = findClosest(tree, dist, start, end, node, start);26 }27 28 return ans;29 }30 31 private void fillDist(List<Integer>[] tree, int start, int u, int d, int[][] dist) {32 dist[start][u] = d;33 for (final int v : tree[u])34 if (dist[start][v] == -1)35 fillDist(tree, start, v, d + 1, dist);36 }37 38 private int findClosest(List<Integer>[] tree, int[][] dist, int u, int end, int node, int ans) {39 for (final int v : tree[u])40 if (dist[v][end] < dist[u][end])41 return findClosest(tree, dist, v, end, node, dist[ans][node] < dist[v][node] ? ans : v);42 return ans;43 }44}45