---
# System prepended metadata

title: 1310. XOR Queries of a Subarray
tags: [Leetcode, Bit Manipulation, XOR, Medium]

---

# 1310. XOR Queries of a Subarray
###### tags: `Leetcode` `Medium` `Bit Manipulation` `XOR`
Link: https://leetcode.com/problems/xor-queries-of-a-subarray/
## 思路 $O(N)$ $O(1)$
In-place calculate the prefix XOR of input A.

For each query ```[i, j]```,
```
if i == 0, query result = A[j]
if i != 0, query result = A[i - 1] ^ A[j]
```
解释: 相当于是把从0到i-1的数字和从0到j的数字一起xor了一遍, 所以从0到i-1的数字被xor了两遍 所以相当于从0到i-1已经被消除了 
## Code
```java=
class Solution {
    public int[] xorQueries(int[] arr, int[][] queries) {
        for(int i=1; i<arr.length; i++){
            arr[i] = arr[i-1]^arr[i];
        }
        int[] ans = new int[queries.length];
        for(int i=0; i<queries.length; i++){
            int[] query = queries[i];
            if(query[0]==0) ans[i]=arr[query[1]];
            else ans[i] = arr[query[1]] ^ arr[query[0]-1];
        }
        return ans;
    }
}
```