XOR Queries of a Subarray - Prefix XOR [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Prefix XOR
XORing a number with itself cancels itself out.
i.e: a = a ^ b ^ b
Store the prefix XOR and use pXor[j + 1] ^ pXor[i]
to get the range XOR of numbers between indices i
and j
.
n = length of arr
, m = number of queries
Time Complexity: O(n + m)
Space Complexity: O(n)
excluding output
function xorQueries(arr, queries) {
let n = arr.length, pXor = Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
pXor[i] = pXor[i - 1] ^ arr[i - 1];
}
let answer = [];
for (let [left, right] of queries) {
answer.push(pXor[right + 1] ^ pXor[left]);
}
return answer;
};
- Get link
- X
- Other Apps
Comments
Post a Comment