Given two integers l and r, return the bitwise XOR of every integer in the inclusive range [l, r] — that is, l ^ (l+1) ^ (l+2) ^ ... ^ r.
Input: l = 1, r = 4 Output: 4 1 ^ 2 ^ 3 ^ 4 = 4.
Input: l = 3, r = 9 Output: 2 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 8 ^ 9 = 2.
Input: l = 5, r = 5 Output: 5 A single-element range is just that element.
- 1 <= l <= r <= 10^9
XORing a whole range one number at a time works, but for a range up to a billion wide it's far too slow. The escape is a small, beautiful fact: the running XOR 0 ^ 1 ^ 2 ^ ... ^ n repeats on a period of four. Once you know XOR(0..n) in O(1), any range answer is two lookups.
x ^ x = 0 and x ^ 0 = x — repeated values cancel, which is what makes the pattern collapse.f(l..r) = F(r) ^ F(l-1).n mod 4 to pick which case of the pattern applies.“Is the range inclusive of both ends?”
Yes — both l and r are included in the XOR.
“How large can l and r be?”
Up to about a billion, so a per-element loop can be far too slow — an O(1) formula is the target.
“Why does F(l-1) remove the unwanted part?”
Because everything below l appears in both F(r) and F(l-1) and cancels under XOR, leaving exactly l..r.
XOR of a range is like a prefix sum: XOR(l..r) = prefix(r) XOR prefix(l-1).
And prefix(n) = XOR of 0..n has a period-4 closed form.
So both prefixes are O(1), and the whole thing is constant time.
The period-4 pattern of F(n) = XOR(0..n)
n: 0 1 2 3 4 5 6 7 8 9 ...
F(n): 0 1 3 0 4 1 7 0 8 1 ...
^-- every n % 4 == 3 resets F(n) to 0
n % 4 == 0 -> n
n % 4 == 1 -> 1
n % 4 == 2 -> n + 1
n % 4 == 3 -> 0
Just like sums, XOR(l..r) = F(r) ^ F(l-1). The shared prefix 0..(l-1) cancels itself, isolating the range you want.
Grouping consecutive numbers shows F(n) cycles every four: n, 1, n+1, 0 for n % 4 = 0, 1, 2, 3. That makes F(n) an O(1) table lookup — no loop.
With F in O(1), the whole answer is F(r) ^ F(l-1) — two evaluations and one XOR, independent of how wide the range is.
| Loop the range | Prefix XOR formula | |
|---|---|---|
| Idea | XOR every integer from l to r | F(r) ^ F(l-1) via the period-4 closed form |
| Time | O(r - l) | O(1) |
| Space | O(1) | O(1) |
Both use constant space, but only the formula is independent of the range width — essential when r - l can be a billion. Full code is in the Approaches selector below.
Key takeaway
XOR over a range is a prefix problem: XOR(l..r) = F(r) ^ F(l-1), where F(n) = XOR(0..n) has the period-4 closed form n, 1, n+1, 0 for n % 4 = 0, 1, 2, 3. That turns a billion-step loop into two table lookups.
F(n):
n % 4 == 0 -> n
n % 4 == 1 -> 1
n % 4 == 2 -> n + 1
n % 4 == 3 -> 0
answer = F(r) XOR F(l - 1)