- 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
- 41 lines of Java from the credited upstream file 2564.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 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 int[][] substringXorQueries(String s, int[][] queries) {3 final int MAX_BIT = 30;4 int[][] ans = new int[queries.length][2];5 6 Map<Integer, Pair<Integer, Integer>> valToLeftAndRight = new HashMap<>();7 8 for (int left = 0; left < s.length(); ++left) {9 int val = 0;10 if (s.charAt(left) == '0') {11 12 if (!valToLeftAndRight.containsKey(0))13 valToLeftAndRight.put(val, new Pair<>(left, left));14 continue;15 }16 final int maxRight = Math.min(s.length(), left + MAX_BIT);17 for (int right = left; right < maxRight; ++right) {18 val = val * 2 + s.charAt(right) - '0';19 if (!valToLeftAndRight.containsKey(val))20 valToLeftAndRight.put(val, new Pair<>(left, right));21 }22 }23 24 for (int i = 0; i < queries.length; ++i) {25 final int first = queries[i][0];26 final int second = queries[i][1];27 final int val = first ^ second;28 Pair<Integer, Integer> leftAndRight = valToLeftAndRight.get(val);29 if (leftAndRight == null) {30 ans[i] = new int[] {-1, -1};31 } else {32 final int left = leftAndRight.getKey();33 final int right = leftAndRight.getValue();34 ans[i] = new int[] {left, right};35 }36 }37 38 return ans;39 }40}41