XOR of numbers in a given range

Pattern: XOR tricks

medium

The XOR of 1..n follows a pattern of period 4 — n, 1, n + 1, 0. So the XOR of l..r is xorUpTo(r) ^ xorUpTo(l - 1), with no loop at all.

The problem

Given two whole numbers l ≤ r (both at least 1), return l ^ (l + 1) ^ … ^ r. For example, l = 3, r = 5 gives 2, and l = 1, r = 3 gives 0.

The link above is a takeUforward practice page. This guide's function name findRangeXOR is its own; check the page for its exact name.

Think first

  • How is this like a prefix sum?
  • Work out 1 ^ 2 ^ … ^ n for n = 1 to 8. What pattern do you see?
  • Why does the prefix up to l - 1 cancel?

Hints

    Brute force, and why it fails

    XOR every number from l to r: O(r - l). The pattern gives O(1).

    The key insight

    Every block of four numbers starting at a multiple of 4 XORs to 0, because the top bits cancel in pairs and the bottom two bits are 00, 01, 10, 11. That is why the prefix repeats every 4.

    Dry run

    l3
    r5

    l = 3 and r = 5. We need 3 ^ 4 ^ 5.

    Step 1 of 4

    The plan

    xorUpTo(n): return [n, 1, n + 1, 0][n mod 4]
    return xorUpTo(r) ^ xorUpTo(l - 1)
    

    Complexity

    Time
    O(1)
    Space
    O(1)

    Two lookups.

    Edge cases

    • l = r: the number itself.
    • l = 1: just xorUpTo(r), since xorUpTo(0) = 0.
    • Large ranges: no loop is needed.
    I've built my logic, show the code

    Java

    class Solution {
        public int findRangeXOR(int l, int r) {
            return xorUpTo(r) ^ xorUpTo(l - 1);     // the prefix up to l - 1 cancels out
        }
    
        private int xorUpTo(int n) {                // 1 ^ 2 ^ ... ^ n repeats with period 4
            switch (n % 4) {
                case 0: return n;
                case 1: return 1;
                case 2: return n + 1;
                default: return 0;
            }
        }
    }

    C++

    class Solution {
    public:
        int findRangeXOR(int l, int r) {
            return xorUpTo(r) ^ xorUpTo(l - 1);     // the prefix up to l - 1 cancels out
        }
    
        int xorUpTo(int n) {                        // 1 ^ 2 ^ ... ^ n repeats with period 4
            switch (n % 4) {
                case 0: return n;
                case 1: return 1;
                case 2: return n + 1;
                default: return 0;
            }
        }
    };

    Python

    class Solution:
        def findRangeXOR(self, l: int, r: int) -> int:
            def xor_up_to(n: int) -> int:           # 1 ^ 2 ^ ... ^ n repeats with period 4
                return [n, 1, n + 1, 0][n % 4]
    
            return xor_up_to(r) ^ xor_up_to(l - 1)  # the prefix up to l - 1 cancels out

    Common mistakes

    • Using xorUpTo(l) instead of xorUpTo(l - 1), which removes l itself.
    • Mixing up the order of the four cases.
    • Looping when r is huge.

    Similar problems