- 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
- 40 lines of Java from the credited upstream file 2097.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 3 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[][] validArrangement(int[][] pairs) {3 List<int[]> ans = new ArrayList<>();4 Map<Integer, Deque<Integer>> graph = new HashMap<>();5 Map<Integer, Integer> outDegree = new HashMap<>();6 Map<Integer, Integer> inDegrees = new HashMap<>();7 8 for (int[] pair : pairs) {9 final int start = pair[0];10 final int end = pair[1];11 graph.putIfAbsent(start, new ArrayDeque<>());12 graph.get(start).push(end);13 outDegree.merge(start, 1, Integer::sum);14 inDegrees.merge(end, 1, Integer::sum);15 }16 17 final int startNode = getStartNode(graph, outDegree, inDegrees, pairs);18 euler(graph, startNode, ans);19 Collections.reverse(ans);20 return ans.stream().toArray(int[][] ::new);21 }22 23 private int getStartNode(Map<Integer, Deque<Integer>> graph, Map<Integer, Integer> outDegree,24 Map<Integer, Integer> inDegrees, int[][] pairs) {25 for (final int u : graph.keySet())26 if (outDegree.getOrDefault(u, 0) - inDegrees.getOrDefault(u, 0) == 1)27 return u;28 return pairs[0][0]; 29 }30 31 private void euler(Map<Integer, Deque<Integer>> graph, int u, List<int[]> ans) {32 Deque<Integer> stack = graph.get(u);33 while (stack != null && !stack.isEmpty()) {34 final int v = stack.pop();35 euler(graph, v, ans);36 ans.add(new int[] {u, v});37 }38 }39}40