1310. XOR Queries of a Subarray
https://leetcode.com/problems/xor-queries-of-a-subarray/
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] = 8Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]class Solution {
public:
vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
const int N = arr.size();
vector<int> prexors(N, 0), res;
for (int i = 0, prexor = 0; i < N; ++i) {
prexor ^= arr[i];
prexors[i] = prexor;
}
for (const auto &q : queries) {
res.push_back(prexors[q[1]] ^ (q[0] == 0 ? 0 : prexors[q[0] - 1]));
}
return res;
}
};Last updated