Skip to content

1310. XOR Queries of a Subarray 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
    vector<int> ans;
    vector<int> xors(arr.size() + 1);

    for (int i = 0; i < arr.size(); ++i)
      xors[i + 1] ^= xors[i] ^ arr[i];

    for (const vector<int>& q : queries)
      ans.push_back(xors[q[0]] ^ xors[q[1] + 1]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int[] xorQueries(int[] arr, int[][] queries) {
    int[] ans = new int[queries.length];
    int[] xors = new int[arr.length + 1];

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

    int i = 0;
    for (int[] q : queries)
      ans[i++] = xors[q[0]] ^ xors[q[1] + 1];

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
    ans = []
    xors = [0] * (len(arr) + 1)

    for i, a in enumerate(arr):
      xors[i + 1] ^= xors[i] ^ a

    for l, r in queries:
      ans.append(xors[l] ^ xors[r + 1])

    return ans