1310. XOR Queries of a Subarray

Description

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

Tags

Bit Manipulation

Solution

A skilled application of the "prefix sum" technique can help us solve "range sum" problems with lower time complexity.

We first build a prefix sum array prefix where prefix[i] = arr[:i+1]. Then, we initialize a result array ans with the length of queries, and, based on the knowledge that N(N+1)...M=[12...(N+1)][1...M1M]N \oplus (N+1) \oplus ... \oplus M = [1 \oplus 2 \oplus ... \oplus (N+1)] \oplus [1 \oplus ... \oplus M-1 \oplus M] , we can obtain the result of a query [l, r] is prefix[l-1] ^ prefix[r]. If l == 0, the result is just prefix[r]. At last, we return ans.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(n)O(n)

Code

func xorQueries(arr []int, queries [][]int) []int {
	ans, prefix := make([]int, len(queries)), make([]int, len(arr))
	prefix[0] = arr[0]
	for i := 1; i < len(prefix); i++ {
		prefix[i] = prefix[i-1] ^ arr[i]
	}
	for i, query := range queries {
		if query[0] == 0 {
			ans[i] = prefix[query[1]]
		} else {
			ans[i] = prefix[query[0]-1] ^ prefix[query[1]]
		}
	}
	return ans
}

Last updated

Was this helpful?