1310. XOR Queries of a Subarray
SourceWeekly Contest 170 Q2DifficultyMediumRating1459
Description
You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].
For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).
Return an array answer where answer[i] is the answer to the ith 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 * 1041 <= arr[i] <= 109queries[i].length == 20 <= lefti <= righti < arr.length
Solutions
Solution 1: Prefix XOR
Thinking
Each query asks for a range XOR. XORing from \(l\) to \(r\) on the fly is quadratic in the number of queries. Because \(x \oplus x = 0\), a prefix \(s[i]=\textit{arr}[0]\oplus\cdots\oplus\textit{arr}[i-1]\) yields \([l,r]\) as \(s[r+1]\oplus s[l]\). One linear build, then \(O(1)\) per query.
We can use a prefix XOR array \(s\) of length \(n+1\) to store the prefix XOR results of the array \(\textit{arr}\), where \(s[i] = s[i-1] \oplus \textit{arr}[i-1]\). That is, \(s[i]\) represents the XOR result of the first \(i\) elements of \(\textit{arr}\).
For a query \([l, r]\), we can obtain:
Time complexity is \(O(n+m)\), and space complexity is \(O(n)\). Here, \(n\) and \(m\) are the lengths of the array \(\textit{arr}\) and the query array \(\textit{queries}\), respectively.
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |