# 1310. 子数组异或查询

<https://leetcode-cn.com/problems/xor-queries-of-a-subarray/>

## 题目描述

```
有一个正整数数组 arr，现给你一个对应的查询数组 queries，其中 queries[i] = [Li, Ri]。

对于每个查询 i，请你计算从 Li 到 Ri 的 XOR 值（即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri]）作为本次查询的结果。

并返回一个包含给定查询 queries 所有结果的数组。



示例 1：

输入：arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
输出：[2,7,14,8]
解释：
数组中元素的二进制表示形式是：
1 = 0001
3 = 0011
4 = 0100
8 = 1000
查询的 XOR 值为：
[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
示例 2：

输入：arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
输出：[8,0,4,4]


提示：

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

## 前置知识

* [前缀和](https://github.com/azl397985856/leetcode/blob/master/thinkings/prefix.md)

## 公司

* 暂无

## 暴力法

### 思路

最直观的思路是双层循环即可，果不其然超时了。

### 代码

```python

class Solution:
    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
 		res = []
        for (L, R) in queries:
            i = L
            xor = 0
            while i <= R:
                xor ^= arr[i]
                i += 1
            res.append(xor)
        return res
```

## 前缀表达式

### 思路

比较常见的是前缀和，这个概念其实很容易理解，即一个数组中，第 n 位存储的是数组前 n 个数字的和。

对 \[1,2,3,4,5,6] 来说，其前缀和可以是 pre=\[1,3,6,10,15,21]。我们可以使用公式 pre\[𝑖]=pre\[𝑖−1]+nums\[𝑖]得到每一位前缀和的值，从而通过前缀和进行相应的计算和解题。其实前缀和的概念很简单，但困难的是如何在题目中使用前缀和以及如何使用前缀和的关系来进行解题。

这道题是对前缀异或。用代码表示就是：

```
pre[0] = 0
pre[i] = arr[0] ^ arr[1] ^ ... ^ arr[i - 1]
```

> ^ 表示异或

其中 pre 就是前缀异或数组，其本质和前缀和类似。接下来对一个区间进行异或，比如对 nums 的\[0,2] 范围进行异或应该是 `nums[0] ^ nums[1] ^ nums[2]`。建立了 pre 数组之后，我们就可以使用如下方式计算，而不是类似`nums[0] ^ nums[1] ^ nums[2]`的区间遍历形式。

```
pre[Li] ^ pre[Ri + 1] = (arr[0] ^ ... ^ arr[Li - 1]) ^ (arr[0] ^ ... ^ arr[Ri])
                      = (arr[0] ^ ... ^ arr[Li - 1]) ^ (arr[0] ^ ... ^ arr[Li - 1]) ^ (arr[Li] ^ ... ^ arr[Ri])
                      = (arr[Li] ^ ... ^ arr[Ri])
                      = arr[Li] ^ ... ^ arr[Ri]
```

上面成立的前提是异或的一个重要性质 `x ^ y ^ x = y`。用自然语言来说就是异或一组数字，两两相同的会抵消，而上面的除了区间\[Li,Ri]内的数，其他数都出现了两次，因此会被抵消。这样就达到了我们的目的。

也就是说如果要计算\[Li,Ri] 的异或，不再需要遍历 \[Li,Ri] 区间内的所有元素，而是直接用 pre\[Li] ^ pre\[Ri + 1] 计算即可。时间复杂度从 $O(R)$ 降低到了 $O(1)$， 其中 R 为区间长度，即 Ri - Li + 1。

> 之所以是 pre\[Li] ^ pre\[Ri + 1]，而不是 pre\[Li - 1] ^ pre\[Ri] 是因为 pre 中我使用了一个虚拟数字 0，如果你没有用到这个，则需要代码有所调整。

![](https://p.ipic.vip/gea0wi.jpg)

### 代码

代码支持 Python3，Java，C++：

Python Code：

```python
#
# @lc app=leetcode.cn id=1218 lang=python3
#
# [1218] 最长定差子序列
#

# @lc code=start


class Solution:
    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
		pre = [0]
        res = []
        for i in range(len(arr)):
            pre.append(pre[i] ^ arr[i])
        for (L, R) in queries:
            res.append(pre[L] ^ pre[R + 1])
        return res

# @lc code=end
```

Java Code：

```java
  public int[] xorQueries(int[] arr, int[][] queries) {

        int[] preXor = new int[arr.length];
        preXor[0] = 0;

        for (int i = 1; i < arr.length; i++)
            preXor[i] = preXor[i - 1] ^ arr[i - 1];

        int[] res = new int[queries.length];

        for (int i = 0; i < queries.length; i++) {

            int left = queries[i][0], right = queries[i][1];
            res[i] = arr[right] ^ preXor[right] ^ preXor[left];
        }

        return res;
    }

```

C++ Code:

```
class Solution {
public:
    vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
        vector<int>res;
        for(int i=1; i<arr.size(); ++i){
            arr[i]^=arr[i-1];
        }
        for(vector<int>temp :queries){
            if(temp[0]==0){
                res.push_back(arr[temp[1]]);
            }
            else{
                res.push_back(arr[temp[0]-1]^arr[temp[1]]);
            }
        }
        return res;
    }
};
```

**复杂度分析**

其中 N 为数组 arr 长度， M 为 queries 的长度。

* 时间复杂度：$O(N \* M)$
* 空间复杂度：$O(N)$

## 关键点解析

* 异或的性质 x ^ y ^ x = y
* 前缀表达式

## 相关题目

* [303. 区域和检索 - 数组不可变](https://leetcode-cn.com/problems/range-sum-query-immutable/description/)

![](https://p.ipic.vip/b5patl.jpg)

* [1186.删除一次得到子数组最大和](https://lucifer.ren/blog/2019/12/11/leetcode-1186/)

大家对此有何看法，欢迎给我留言，我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库：<https://github.com/azl397985856/leetcode> 。 目前已经 37K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。 ![](https://p.ipic.vip/h9nm77.jpg)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leetcode-solution-leetcode-pp.gitbook.io/leetcode-solution/medium/1310.xor-queries-of-a-subarray.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
