Substring XOR Queries - Sliding Window [JS]
Solution: Sliding Window
From each [first, second]
of each query, we can deduct the value that we need.
- There can only be one value:
val = first ^ second
Map each first ^ second
to the initial indices [-1, -1]
. There can be multiply queries needing the same value.
A number has at most 32 bits.
Use a sliding window for each length (1 to 32),
- Maintain the value of the current window
- If
queriesMap
contains the value of the current window, update the indices in the map.
At the end, go through each query and get the indices saved in queriesMap
.
n = length of s
, m = number of queries
Time Complexity: O(32 * n + m)
Space Complexity: O(m)
var substringXorQueries = function(s, queries) {
let n = s.length, queriesMap = new Map();
for (let i = 0; i < queries.length; i++) {
let [first, second] = queries[i];
queriesMap.set(first ^ second, [-1, -1]);
}
for (let len = 32; len >= 1; len--) {
let val = 0;
for (let i = 0; i < n; i++) {
val = (val << 1) | Number(s[i]);
if (i >= len) {
if ((val >> len) & 1) val = val ^ (1 << len); // remove the (i-len)th bit
}
if (i >= len - 1) {
if (queriesMap.has(val)) {
let [start, end] = queriesMap.get(val);
let currLen = end - start + 1;
if (currLen !== len || start === -1) {
queriesMap.set(val, [i - len + 1, i]);
}
}
}
}
}
return queries.map(([first, second]) => queriesMap.get(first ^ second));
};
Comments
Post a Comment