XOR Queries of a Subarray

Answer many questions of the form "what is the XOR of this stretch of the array?", each with one XOR of two stored values.

Given an array arr of positive integers and a list of queries, answer every query. A query [left, right] asks for the XOR (exclusive or) of arr[left], arr[left + 1], and so on up to arr[right]. For example, 3 XOR 4 is 7. Return the answers in the same order as the queries.

Example 1
Input: arr = [1, 3, 4, 8], queries = [[0, 1], [1, 2], [0, 3], [3, 3]]
Output: [2, 7, 14, 8]
Example 2
Input: arr = [4, 8, 2, 10], queries = [[2, 3], [1, 3], [0, 0], [0, 3]]
Output: [8, 0, 4, 4]
Solution

The Idea

Along a highway, small posts show how many kilometres you have driven from the start. To know how far it is from exit 2 to exit 5, nobody measures that stretch again. You read the two posts and subtract. This problem asks the same kind of question about a stretch of an array, with XOR in place of distance.

What does XOR do to two numbers? Write them in binary. In Example 1, 3 is 0011 and 4 is 0100, with bit position 0 on the right. XOR goes through the positions one by one and writes a 1 where exactly one of the two numbers has a 1. For 3 and 4 that gives 0111, which is 7. In Java the operator is ^, so 3 ^ 4 is 7.

Now walk through Example 1. The query [1, 2] asks for 3 ^ 4, which is 7. The query [0, 3] asks for 1 ^ 3 ^ 4 ^ 8, which is 14. Each query could be answered by going through its stretch of the array. But [0, 1], [1, 2] and [0, 3] all read the 3 at index 1 again. Can the work done once be shared by every query, as the kilometre posts share it?

It can, because XOR undoes itself. In 1 ^ 1, every bit position holds the same bit twice, so every position gives 0, and the result is 0. XOR with 0 changes nothing, so 1 ^ 3 ^ 4 ^ 1 is just 3 ^ 4. XOR-ing a number a second time removes it, the way subtracting removes what was added.

So keep a post at every point of the array: the XOR of all numbers before that point. This is a running XOR, kept in an array named prefix, where prefix[i] is the XOR of the first i numbers. The picture shows prefix for Example 1, under the array it is built from.

The array 1, 3, 4, 8 with each number in binary, and below it the running XOR prefix: 0, 1, 2, 6, 14. For the query [1, 2], prefix[3] = 6 (0110) XOR prefix[1] = 1 (0001) gives 0111, which is 7, the XOR of 3 and 4.

The row labelled running XOR starts with prefix[0] = 0, for no numbers at all. Each next box XORs in one more number: 0, then 1, then 1 ^ 3 = 2, then 2 ^ 4 = 6, then 6 ^ 8 = 14. The query [1, 2] is marked in orange on the arr row, and the two teal boxes answer it.

In the bit table at the bottom, prefix[3] = 6 is 1 ^ 3 ^ 4, and prefix[1] is arr[0], which is 1. XOR them and the two 1s cancel, leaving 3 ^ 4. The orange row shows the result, 0111, which is 7. Two stored values answer the query, however long the stretch is.

Solution Approach

Looping over each stretch works, but it repeats work. The running XOR instead needs three decisions: storing the running XOR, picking the two entries for a query, and checking that the answer cannot overflow.

Looping over each stretch

What does the simple way cost? For each query, start from 0 and XOR in arr[left] through arr[right]. A query may cover the whole array, so with n numbers and q queries this takes up to n × q steps. With 10,000 numbers and 10,000 such queries, that is 100 million XORs, most of them repeating work another query already did.

Storing the running XOR

How long should prefix be? One slot longer than arr. Slot 0 holds 0, for no numbers, and each later slot is prefix[i + 1] = prefix[i] ^ arr[i]. Thanks to that extra slot, a query that starts at index 0 needs no special case. It XORs with prefix[0], which is 0 and changes nothing.

Picking the two entries

Which two entries answer [left, right]? The entry prefix[right + 1] holds arr[0] through arr[right]. The entry prefix[left] holds arr[0] through arr[left - 1], exactly the numbers before the stretch. XOR-ing the two cancels those numbers and leaves arr[left] through arr[right]. In the picture, the query [1, 2] uses prefix[3] and prefix[1].

Why the answer fits in an int

Could the answer grow too big, as a sum of many numbers can? A Java int has 32 bits in two's complement form, where a 1 at position 31 makes the number negative. Every positive value in arr has a 0 there. XOR handles each position on its own and never carries into the next, so the answer has a 1 only where some input has one. Position 31 stays 0, and the answer is always a positive int or 0.

Java Solution

The method xorQueries works in these steps:

  1. First, create the array prefix with arr.length + 1 slots. Java fills a new int array with zeros, so prefix[0] is already 0.
  2. A loop with index i walks along arr and sets prefix[i + 1] = prefix[i] ^ arr[i], one more number each time.
  3. Create the array answer, with one slot per query. A second loop, with index q, reads each query's left and right.
  4. Set answer[q] to prefix[right + 1] ^ prefix[left]. When the second loop ends, the method returns answer.

The main method runs both examples, an array of three equal numbers, three large numbers that include Integer.MAX_VALUE, and an array with a single number.

Java
import java.util.Arrays;

public class XorQueries {

    public static int[] xorQueries(int[] arr, int[][] queries) {
        // prefix[i] = arr[0] ^ arr[1] ^ ... ^ arr[i - 1], and prefix[0] = 0
        int[] prefix = new int[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            prefix[i + 1] = prefix[i] ^ arr[i];
        }
        int[] answer = new int[queries.length];
        for (int q = 0; q < queries.length; q++) {
            int left = queries[q][0];
            int right = queries[q][1];
            // prefix[left] is in both, so XOR-ing it again cancels it
            answer[q] = prefix[right + 1] ^ prefix[left];
        }
        return answer;
    }

    public static void main(String[] args) {
        int[][] queries1 = {{0, 1}, {1, 2}, {0, 3}, {3, 3}};
        System.out.println(Arrays.toString(xorQueries(new int[] {1, 3, 4, 8}, queries1)));
        int[][] queries2 = {{2, 3}, {1, 3}, {0, 0}, {0, 3}};
        System.out.println(Arrays.toString(xorQueries(new int[] {4, 8, 2, 10}, queries2)));
        int[][] queries3 = {{0, 1}, {0, 2}, {1, 1}};
        System.out.println(Arrays.toString(xorQueries(new int[] {7, 7, 7}, queries3)));
        int[] big = {1000000000, 999999999, 2147483647};
        int[][] queries4 = {{0, 1}, {0, 2}};
        System.out.println(Arrays.toString(xorQueries(big, queries4)));
        System.out.println(Arrays.toString(xorQueries(new int[] {5}, new int[][] {{0, 0}})));
    }
}

Running it prints:

Output
[2, 7, 14, 8]
[8, 0, 4, 4]
[0, 7, 7]
[1023, 2147482624]
[5]

The lines [2, 7, 14, 8] and [8, 0, 4, 4] match the two examples. In Example 2, the query [1, 3] gives 0 because 8 ^ 2 is 10, and 10 XOR 10 cancels.

The line [0, 7, 7] comes from [7, 7, 7]. Two 7s cancel to 0, a third brings 7 back, and the query [1, 1] returns its one number.

Look at [1023, 2147482624]. In binary, 1,000,000,000 and 999,999,999 agree in every bit above position 9 and differ in all ten bits from position 9 down to 0, so their XOR is ten 1s, which is 1023. Adding Integer.MAX_VALUE, 2,147,483,647, to their sum would not fit in an int. The XOR of all three is 2,147,482,624, still a valid int. The last line, [5], shows that a one-number array works too.

The + 1 in prefix[right + 1] is easy to drop. A separate run on Example 1 with prefix[right] ^ prefix[left] printed [1, 3, 6, 0] instead of [2, 7, 14, 8]. Each answer leaves out arr[right], and [3, 3] becomes 0 because both entries are the same.

Complexity

Building the running XOR takes one pass over arr, and each query then costs one XOR.

  • Time: O(n + q), because the first loop visits each of the n numbers once, and each of the q queries reads two entries of prefix and XORs them.
  • Space: O(n) besides the output, because prefix keeps n + 1 running values, while answer, with its q entries, is the result itself.

With addition in place of XOR, the same idea answers sums over a stretch, where the shared part is subtracted: see Range Sum Query - Immutable.