XOR Queries of a Subarray - Problem

You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].

For each query i, compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]).

Return an array answer where answer[i] is the answer to the ith query.

Input & Output

Example 1 — 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 — Single Element Query
$ Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,4,4,8]
💡 Note: Query [2,3]: 2 ^ 10 = 8. Query [1,3]: 8 ^ 2 ^ 10 = 4. Query [0,0]: 4 = 4. Query [0,3]: 4 ^ 8 ^ 2 ^ 10 = 8.
Example 3 — Edge Case
$ Input: arr = [5], queries = [[0,0]]
Output: [5]
💡 Note: Single element array with single element query returns the element itself.

Constraints

  • 1 ≤ arr.length ≤ 3 × 104
  • 1 ≤ arr[i] ≤ 109
  • 1 ≤ queries.length ≤ 3 × 104
  • queries[i].length == 2
  • 0 ≤ lefti ≤ righti < arr.length

Visualization

Tap to expand
INPUTALGORITHMRESULTArray: [1,3,4,8]1348Queries:[0,1] [1,2] [0,3] [3,3]1Build Prefix XOR2prefix = [0,1,2,6,14]3For each query:4prefix[r+1] ^ prefix[l]Answer Array:27148Query Results:[0,1]: 1^3 = 2[1,2]: 3^4 = 7[0,3]: 1^3^4^8 = 14[3,3]: 8 = 8Key Insight:XOR has the property A ^ B ^ B = A, enabling prefix arrays to compute any range XOR in O(1) timeTutorialsPoint - XOR Queries of a Subarray | Prefix XOR Approach
Asked in
Amazon 25 Microsoft 18
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen