Advanced Coding Patterns for Interviews

0% completed

Previous
Next
XOR Queries of a Subarray (medium)

Problem Statement

You are given an array arr containing integers greater than 0. Additionally, you are given the array of queries where queries[i] = [left<sub>i</sub>, right<sub>i</sub>].

For each query, compute the XOR of the elements in arr from index left<sub>i</sub> to right<sub>i</sub> (inclusive)

Return an array answer where answer[i] represents the result of the i<sup>th</sup> query.

Examples

Example 1:

  • Input: arr = [2, 4, 7, 3], queries = [[0, 1], [1, 3], [0, 2]]
  • Expected Output: [6, 0, 1]
  • Explanation:
    • For the first query [0, 1], XOR of elements from index 0 to 1: 2 XOR 4 = 6
    • For the second query [1, 3], XOR of elements from index 1 to 3: 4 XOR 7 XOR 3 = 0
    • For the third query [0, 2], XOR of elements from index 0 to 2: 2 XOR 4 XOR 7 = 1

Example 2:

  • Input: arr = [5, 9, 12, 6], queries = [[2, 3], [0, 2], [1, 2]]
  • Expected Output: [10, 0, 5]
  • Explanation:
    • For the first query [2, 3], XOR of elements from index 2 to 3: 12 XOR 6 = 10
    • For the second query [0, 2], XOR of elements from index 0 to 2: 5 XOR 9 XOR 12 = 0
    • For the third query [1, 2], XOR of elements from index 1 to 2: 9 XOR 12 = 5

Example 3:

  • Input: arr = [1, 3, 5, 7, 9], queries = [[1, 4], [0, 3], [2, 4]]
  • Expected Output: [8, 0, 11]
  • Explanation:
    • For the first query [1, 4], XOR of elements from index 1 to 4: 3 XOR 5 XOR 7 XOR 9 = 8
    • For the second query [0, 3], XOR of elements from index 0 to 3: 1 XOR 3 XOR 5 XOR 7 = 0
    • For the third query [2, 4], XOR of elements from index 2 to 4: 5 XOR 7 XOR 9 = 11

Constraints:

  • 1 <= arr.length, queries.length <= 3 * 10<sup>4</sup>
  • 1 <= arr[i] <= 10<sup>9</sup>
  • queries[i].length == 2
  • 0 <= left<sub>i</sub> <= right<sub>i</sub> < arr.length

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next