- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 37 lines of Java from the credited upstream file 1182.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 List<Integer> shortestDistanceColor(int[] colors, int[][] queries) {3 final int NUM_COLOR = 3;4 final int n = colors.length;5 List<Integer> ans = new ArrayList<>();6 7 int[][] left = new int[n][NUM_COLOR + 1];8 9 int[][] right = new int[n][NUM_COLOR + 1];10 11 int[] colorToClosestIndex = {0, -1, -1, -1}; 12 for (int i = 0; i < n; ++i) {13 colorToClosestIndex[colors[i]] = i;14 for (int c = 1; c <= NUM_COLOR; ++c)15 left[i][c] = colorToClosestIndex[c];16 }17 18 colorToClosestIndex = new int[] {0, -1, -1, -1}; 19 for (int i = n - 1; i >= 0; --i) {20 colorToClosestIndex[colors[i]] = i;21 for (int c = 1; c <= NUM_COLOR; ++c)22 right[i][c] = colorToClosestIndex[c];23 }24 25 for (int[] query : queries) {26 final int i = query[0];27 final int c = query[1];28 final int leftDist = left[i][c] == -1 ? Integer.MAX_VALUE : i - left[i][c];29 final int rightDist = right[i][c] == -1 ? Integer.MAX_VALUE : right[i][c] - i;30 final int minDist = Math.min(leftDist, rightDist);31 ans.add(minDist == Integer.MAX_VALUE ? -1 : minDist);32 }33 34 return ans;35 }36}37