1005. Range XOR Lookup

Medium3.5 points estimatedArrayBit ManipulationPrefix Sum3 hints

A sensor logs a reading nums[i] every second for n seconds. Each entry [a, b] of queries selects the stretch of seconds from a % n to b % n inclusive (swap the two ends when the first is larger).

For every query return the bitwise XOR of all readings in its stretch. A stretch of one second is just that reading. Return the answers in the order of queries, as an empty array if there are no queries.

Combining the readings one by one for every query is too slow when both the log and the number of queries are large. Aim for O(n + q) time and O(n) space.

Example 1

Input:
nums = [12,5,9,6,10,3]queries = [[0,2],[3,5],[4,1],[2,2]]
Output:
[0,15,0,9]
Explanation:

Window 0..2 gives 12 xor 5 xor 9 = 0; window 3..5 gives 6 xor 10 xor 3 = 15; the pair (4,1) is read as 1..4 and also gives 0; the single position 2 gives 9.

Example 2

Input:
nums = [21,34,8,17], queries = [[1,3],[0,0],[6,9]]
Output:
[59,21,42]
Explanation:

Window 1..3 gives 34 xor 8 xor 17 = 59; position 0 alone gives 21; the pair (6,9) is read modulo 4 as positions 2 and 1, i.e. window 1..2, giving 34 xor 8 = 42.

Constraints

1 ≤ n = nums.length ≤ 2 * 105

0 ≤ nums[i] < 230

0 ≤ q = queries.length ≤ 2000; 0 ≤ a, b ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n + q)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…