-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathNo1310.XOR-queries-of-a-subarray.cs
48 lines (45 loc) · 1.32 KB
/
No1310.XOR-queries-of-a-subarray.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* Difficulty:
* Medium
*
* Desc:
* 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:
* 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 <= 3 * 10^4
* 1 <= arr[i] <= 10^9
* 1 <= queries.length <= 3 * 10^4
* queries[i].length == 2
* 0 <= queries[i][0] <= queries[i][1] < arr.length
*/
public class Solution {
public int[] XorQueries(int[] arr, int[][] queries) {
int[] prefix = new int[arr.Length + 1];
prefix[0] = 1;
for (int i = 0; i < arr.Length; i += 1) {
prefix[i + 1] = prefix[i] ^ arr[i];
}
return queries.Select((int[] query) => prefix[query[1] + 1] ^ prefix[query[0]]).ToArray();
}
}