1310. X O R Queries of a Subarray

1310. XOR Queries of a Subarray #

Problem #

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]

Constraints:

  • 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

Problem Summary #

There is an array of positive integers arr, and now you are given a corresponding query array queries, where queries[i] = [Li, Ri]. For each query i, compute the XOR value from Li to Ri (that is, arr[Li] xor arr[Li+1] xor … xor arr[Ri]) as the result of this query. Return an array containing all results for the given queries queries.

Solution Idea #

  • This problem asks for the XOR of a range, which easily brings range sum to mind. Range sum uses prefix sums, which can reduce a query from O(n) to O(1). Can range XOR also use a similar prefix-sum idea? The answer is yes. Using two properties of XOR, x ^ x = 0 and x ^ 0 = x. Then we have: (Since the XOR symbol ^ is a special character in LaTeX, the author uses \( \oplus \) to represent XOR)

    \[ \begin{aligned}Query(left,right) &=arr[left] \oplus \cdots  \oplus arr[right]\\&=(arr[0] \oplus \cdots  \oplus arr[left-1]) \oplus (arr[0] \oplus \cdots  \oplus arr[left-1]) \oplus (arr[left] \oplus \cdots  \oplus arr[right])\\ &=(arr[0] \oplus \cdots  \oplus arr[left-1]) \oplus (arr[0] \oplus \cdots  \oplus arr[right])\\ &=xors[left] \oplus xors[right+1]\\ \end{aligned} \]

    Solving the problem according to this idea can reduce each query from O(n) to O(1), with an overall time complexity of O(n).

Code #

package leetcode

func xorQueries(arr []int, queries [][]int) []int {
	xors := make([]int, len(arr))
	xors[0] = arr[0]
	for i := 1; i < len(arr); i++ {
		xors[i] = arr[i] ^ xors[i-1]
	}
	res := make([]int, len(queries))
	for i, q := range queries {
		res[i] = xors[q[1]]
		if q[0] > 0 {
			res[i] ^= xors[q[0]-1]
		}
	}
	return res
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文