9. XOR Queries of a Subarray
Given the array arr
of positive integers and the array queries
where queries[i] = [Li, Ri]
, for each query i
compute the XOR of elements from Li
to Ri
(that is, arr[Li]
xor
arr[Li+1]
xor
...
xor
arr[Ri]
). Return an array containing the result for the given queries
.
Example 1:
Example 2:
Approach:(V.IMP)
The XOR trick: If we have a sequence of XOR operations
a ^ b ^ c ^ ...
, then we can remove all pairs of duplicated values without affecting the result.
Commutativity allows us to re-order the applications of XOR so that the duplicated elements are next to each other. Since x ^ x = 0
and a ^ 0 = a
, each pair of duplicated values has no effect on the outcome.
Let’s go through an example of this:
Solution:
Time Complexity: O(n)
Last updated