[LeetCode] XOR Queries of a Subarray

1310. XOR Queries of a Subarray

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> xorQueries(vector<int>& A, vector<vector<int>>& queries) {
vector<int> pxor = {0};
for(int i = 0; i < A.size(); i++) {
pxor.push_back(pxor.back() ^ A[i]);
}
vector<int> res;
for(auto& q : queries) {
int l = q[0], r = q[1];
res.push_back(pxor[l] ^ pxor[r+1]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/19/PS/LeetCode/xor-queries-of-a-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.