XOR Queries of a Subarray Problem
Description
LeetCode Problem 1310.
You are given an array arr of positive integers. You are also given the array queries where queries[i] = [left_i,right_i].
For each query i compute the XOR of elements from left_i to right_i (that is, arr[left_i] XOR arr[left_i + 1] XOR ... XOR arr[right_i] ).
Return an array answer where answer[i] is the answer to the i^th query.
Example 1:
Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8
Example 2:
Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]
Constraints:
1 <= arr.length, queries.length <= 3 * 10^41 <= arr[i] <= 10^9queries[i].length == 20 <= left_i <= right_i < arr.length
Solution
Approach: Prefix XOR
XOR behaves like addition with one extra property: every number is its own inverse, x ^ x = 0. So the same trick as prefix sums works.
Let pre[i] be the XOR of the first i elements, arr[0] ^ ... ^ arr[i - 1], with pre[0] = 0. For a query [l, r], pre[r + 1] is the XOR of arr[0..r] and pre[l] the XOR of arr[0..l - 1]. XOR-ing them cancels the shared part arr[0..l - 1], leaving exactly arr[l] ^ ... ^ arr[r].
For example, with arr = [1,3,4,8] we get pre = [0,1,2,6,14], and the query [1,2] is pre[3] ^ pre[1] = 6 ^ 1 = 7.
Each query is then answered in constant time, instead of walking its whole range.
Complexity: O(n + q) time for n elements and q queries, and O(n) extra space for the prefix array.
class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
# pre[i] is the XOR of arr[0..i-1]; the shared prefix arr[0..l-1] cancels out in pre[r + 1] ^ pre[l].
pre = [0]
for x in arr:
pre.append(pre[-1] ^ x)
return [pre[r + 1] ^ pre[l] for l, r in queries]