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 * 104
1 <= arr[i] <= 109
queries[i].length == 2
0 <= lefti <= righti < arr.length
class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
xors = [0]
for v in arr:
xors.append(xors[-1] ^ v)
return [xors[l] ^ xors[r + 1] for l, r in queries]
class Solution {
public int[] xorQueries(int[] arr, int[][] queries) {
int n = arr.length;
int[] xors = new int[n + 1];
for (int i = 0; i < n; ++i) {
xors[i + 1] = xors[i] ^ arr[i];
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int l = queries[i][0];
int r = queries[i][1];
ans[i] = xors[l] ^ xors[r + 1];
}
return ans;
}
}
/**
* @param {number[]} arr
* @param {number[][]} queries
* @return {number[]}
*/
var xorQueries = function (arr, queries) {
let n = arr.length;
let xors = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
xors[i + 1] = xors[i] ^ arr[i];
}
let res = [];
for (let [l, r] of queries) {
res.push(xors[l] ^ xors[r + 1]);
}
return res;
};
class Solution {
public:
vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
int n = arr.size();
vector<int> xors(n + 1);
for (int i = 0; i < n; ++i) xors[i + 1] = xors[i] ^ arr[i];
vector<int> ans;
for (auto& q : queries) {
int l = q[0], r = q[1];
ans.push_back(xors[l] ^ xors[r + 1]);
}
return ans;
}
};
func xorQueries(arr []int, queries [][]int) []int {
xors := make([]int, len(arr)+1)
for i, v := range arr {
xors[i+1] = xors[i] ^ v
}
var ans []int
for _, q := range queries {
l, r := q[0], q[1]
ans = append(ans, xors[l]^xors[r+1])
}
return ans
}