---
description: https://leetcode.com/problems/xor-queries-of-a-subarray/
---

# 1310. XOR Queries of a Subarray

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]
```

不断查询数组中\[i, j]范围内元素全部异或后的值。不改变数据结构内的值时查询范围用presum思想：res\[0:j]去掉res\[0:i-1]。XOR满足自己和自己相XOR为0，因此让prexors\[j] ^ prexors\[i - 1]就能把\[0:i-1]从中去除。

```cpp
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;
    }
};
```
