XOR of a Given Range

easy

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.

Hints

Looping the whole range is O(r - l) — too slow when the range spans a billion.
Think prefix sums, but with XOR: XOR(l..r) = F(r) XOR F(l-1), where F(n) = XOR(0..n).
F(n) repeats every 4: n, 1, n+1, 0 for n % 4 = 0, 1, 2, 3.

Common doubts

F(r) is XOR(0..r) and F(l-1) is XOR(0..l-1). They share the terms 0..(l-1), which cancel under XOR, leaving exactly l..r.
Pairing consecutive numbers (2k) ^ (2k+1) = 1 makes the running XOR cycle: it returns to 0 at every n where n % 4 == 3, which fixes all four cases.
Using F(l) would cancel the element l itself. F(l-1) keeps l in the range, so the result covers [l, r] inclusive.

Interview follow-ups

The same F(n) formula answers each query in O(1) with no preprocessing, since F has a closed form — no prefix array needed.
Split by residue: the evens and odds each form their own arithmetic pattern, and XOR of an arithmetic-by-2 sequence has its own small closed forms you can derive the same way.

Fun facts

  • The pattern exists because (2k) ^ (2k+1) = 1 for every k, so consecutive pairs collapse to a single 1 that then cancels.
  • The same prefix-XOR idea powers XOR range queries over arrays and is the backbone of many competitive-programming bit tricks.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: l = 1, r = 4
Output: 4
1 ^ 2 ^ 3 ^ 4 = 4.
Example 2
Input: l = 3, r = 9
Output: 2
3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 8 ^ 9 = 2.
Example 3
Input: l = 5, r = 5
Output: 5
A single-element range is just that element.
Constraints

- 1 <= l <= r <= 10^9

Solve this problem →