- 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 2120.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block 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[] executeInstructions(int n, int[] startPos, String s) {3 final int m = s.length();4 final int uMost = startPos[0] + 1;5 final int dMost = n - startPos[0];6 final int lMost = startPos[1] + 1;7 final int rMost = n - startPos[1];8 Map<Character, Pair<Integer, Integer>> moves = new HashMap<>();9 moves.put('L', new Pair<>(0, -1));10 moves.put('R', new Pair<>(0, 1));11 moves.put('U', new Pair<>(-1, 0));12 moves.put('D', new Pair<>(1, 0));13 14 int[] ans = new int[m];15 Map<Integer, Integer> reachX = new HashMap<>();16 Map<Integer, Integer> reachY = new HashMap<>();17 reachX.put(0, m);18 reachY.put(0, m);19 int x = 0;20 int y = 0;21 22 for (int i = m - 1; i >= 0; --i) {23 Pair<Integer, Integer> pair = moves.get(s.charAt(i));24 final int dx = pair.getKey();25 final int dy = pair.getValue();26 x -= dx;27 y -= dy;28 reachX.put(x, i);29 reachY.put(y, i);30 final int out = Math.min(Math.min(reachX.getOrDefault(x - uMost, Integer.MAX_VALUE),31 reachX.getOrDefault(x + dMost, Integer.MAX_VALUE)),32 Math.min(reachY.getOrDefault(y - lMost, Integer.MAX_VALUE),33 reachY.getOrDefault(y + rMost, Integer.MAX_VALUE)));34 ans[i] = out == Integer.MAX_VALUE ? m - i : out - i - 1;35 }36 37 return ans;38 }39}40