#1310
XOR Queries of a Subarray
MediumArrayBit ManipulationPrefix SumPrefix SumBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
By using a prefix XOR array, we can compute the XOR for any subarray in constant time after an initial linear time preprocessing step. This significantly reduces the time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix XOR array where prefix[i] = arr[0] XOR arr[1] XOR ... XOR arr[i].
- 2Step 2: For each query, use the prefix XOR to compute the result as prefix[right] XOR prefix[left - 1] (handle left = 0 case separately).
- 3Step 3: Return the results list.
solution.py13 lines
1def xorQueries(arr, queries):
2 n = len(arr)
3 prefix = [0] * n
4 prefix[0] = arr[0]
5 for i in range(1, n):
6 prefix[i] = prefix[i - 1] ^ arr[i]
7 result = []
8 for left, right in queries:
9 if left == 0:
10 result.append(prefix[right])
11 else:
12 result.append(prefix[right] ^ prefix[left - 1])
13 return resultℹ
Complexity note: The time complexity is O(n) for building the prefix array and O(m) for processing m queries, making it efficient for large inputs.
- 1Using prefix XOR allows for efficient range queries.
- 2XOR has properties that can simplify calculations, such as x ^ x = 0.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.