XOR Queries of a Subarray - Problem
You're given an array arr of positive integers and an array queries where each query specifies a range [left, right].
Your task: For each query, compute the XOR (exclusive OR) of all elements from index left to right (inclusive).
Example: If arr = [1, 3, 4, 8] and we want XOR from index 1 to 3, we calculate: 3 ⊕ 4 ⊕ 8 = 7
The naive approach of recalculating XOR for each query can be very slow for large inputs. Can you find a more efficient solution using the mathematical properties of XOR?
Key XOR Property: a ⊕ a = 0 and a ⊕ 0 = a
Input & Output
example_1.py — Basic Range Queries
$
Input:
arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
›
Output:
[2,7,14,8]
💡 Note:
Query [0,1]: 1⊕3=2, Query [1,2]: 3⊕4=7, Query [0,3]: 1⊕3⊕4⊕8=14, Query [3,3]: 8=8
example_2.py — Single Element Queries
$
Input:
arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
›
Output:
[8,0,4,4]
💡 Note:
Query [2,3]: 2⊕10=8, Query [1,3]: 8⊕2⊕10=0, Query [0,0]: 4=4, Query [0,3]: 4⊕8⊕2⊕10=4
example_3.py — Edge Case - Full Array
$
Input:
arr = [1], queries = [[0,0]]
›
Output:
[1]
💡 Note:
Single element array with single element query returns the element itself
Visualization
Tap to expand
Understanding the Visualization
1
Problem Setup
Array [1,3,4,8] with queries asking for XOR of different ranges
2
Brute Force Issue
Each query requires scanning the entire range - inefficient for multiple queries
3
Prefix XOR Magic
Build prefix array once: [0,1,2,6,14] where prefix[i] = XOR of elements 0 to i-1
4
O(1) Query Resolution
Any range [L,R] = prefix[R+1] ⊕ prefix[L] due to XOR cancellation property
Key Takeaway
🎯 Key Insight: XOR's self-cancelling property (a ⊕ a = 0) enables prefix optimization, transforming O(n×q) brute force into O(n+q) efficiency by preprocessing once and answering queries instantly.
Time & Space Complexity
Time Complexity
O(n + q)
O(n) to build prefix array + O(1) per query for q queries
✓ Linear Growth
Space Complexity
O(n)
Need extra array to store prefix XOR values
⚡ Linearithmic Space
Constraints
- 1 ≤ arr.length, queries.length ≤ 3 × 104
- 1 ≤ arr[i] ≤ 109
- queries[i].length == 2
- 0 ≤ lefti ≤ righti < arr.length
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code