Answer range XOR queries
Reuse prefix cancellation and the four-case XOR pattern for consecutive integers.
Understand the idea
Set prefix[0] = 0 and prefix[i + 1] = prefix[i] XOR a[i]. The XOR of a half-open interval [l, r) is prefix[r] XOR prefix[l]: all earlier elements appear twice and cancel. Unlike sum subtraction, the inverse operation here is XOR itself.
Trace a small example
For [5, 2, 7], prefixes are [0, 5, 7, 0]. The XOR over positions [1, 3) is 0 XOR 5 = 5, matching 2 XOR 7. XOR from 0 through n follows n, 1, n + 1, 0 for n modulo 4 equal to 0, 1, 2, 3.
Conditions and cost
Build prefixes in O(n), then answer each query in O(1). For inclusive [L, R] of nonnegative integers, use F(R) XOR F(L − 1), with a separate L = 0 case to avoid unsigned underflow.
Prefix sum explorer
Query [l, r] is zero-based and inclusive. P[k] stores the total of the first k values; P[0] is zero.
Input array a
Prefix array P
Preprocess once in O(n). Each range sum then takes O(1).
Guided simulation · Change the inputs to test your understanding.
Which expression gives XOR of a[l..r) from a prefix XOR array?
Turn the idea into code
Compute XOR of all integers from 4 through 7.
Give me a hint
Use the four-case pattern or cancel by hand.
Show the explained solution
F(7) = 0 and F(3) = 0, so the range XOR is 0. Directly, 4 XOR 5 = 1 and 6 XOR 7 = 1.
Your notes
Mark complete when you can explain it yourself.