2564. Substring XOR Queries
Explanation:
To solve this problem, we can use a prefix XOR technique along with a hashmap to store the indices of each prefix XOR value encountered. We iterate through the string s
to calculate the prefix XOR values at each position. Then, for each query, we check if there exists a prefix XOR value val
such that val ^ firsti = secondi
in the hashmap. If found, we update the answer with the shortest valid substring.
-
Algorithmic Idea:
- Create a hashmap to store the indices of each prefix XOR value encountered.
- Iterate through the string
s
and calculate the prefix XOR values at each position. - For each query, check if there exists a prefix XOR value
val
such thatval ^ firsti = secondi
in the hashmap. - Update the answer with the shortest valid substring.
-
Time Complexity: O(N) where N is the length of the string
s
. -
Space Complexity: O(N) to store the prefix XOR values in the hashmap.
:
class Solution {
public int[][] findSubstrings(String s, int[][] queries) {
int n = s.length();
int[] prefixXor = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixXor[i + 1] = prefixXor[i] ^ (s.charAt(i) - '0');
}
Map<Integer, Integer> map = new HashMap<>();
int[][] ans = new int[queries.length][2];
for (int i = 0; i < n; i++) {
if (!map.containsKey(prefixXor[i])) {
map.put(prefixXor[i], i);
}
}
for (int i = 0; i < queries.length; i++) {
int left = -1, right = n;
int first = queries[i][0];
int second = queries[i][1];
for (int j = 0; j <= n; j++) {
if (map.containsKey(prefixXor[j] ^ first)) {
int start = map.get(prefixXor[j] ^ first);
if (j - start < right - left) {
left = start;
right = j;
}
}
}
ans[i][0] = left;
ans[i][1] = right - 1;
}
return ans;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.