Skip to main content

XOR Queries Of A Subarray

Examples​

Example 1:

Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]

Example 2:

Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]

Example 3:

Input: arr = [1], queries = [[0,0]]
Output: [1]

Constraints​

  • 1 <= arr.length, queries.length <= 3 * 10^4
  • 1 <= arr[i] <= 10^9
  • queries[i].length == 2
  • 0 <= lefti <= righti < arr.length

Solution​

Written by @ImmidiSivani
from typing import List

class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
n = len(queries)
ans = []
m = len(arr)
prefixXor = [0] * (m + 1)
for i in range(m):
prefixXor[i + 1] = prefixXor[i] ^ arr[i]
for query in queries:
left = query[0]
right = query[1]
ans.append(prefixXor[right + 1] ^ prefixXor[left])
return ans

References​