DSA interview question
A checksum routine for a sequential ID allocator needs the XOR of every ID from L to R, and the ranges can span a billion IDs, so looping is too slow. XOR from 1 to n follows a period-4 pattern: n, 1, n + 1, 0 for n mod 4 = 0, 1, 2, 3, because each aligned block 4k, 4k+1, 4k+2, 4k+3 XORs to 0. And like prefix sums, XOR(L..R) = XOR(1..R) ^ XOR(1..L−1), because the shared prefix cancels.
Example: L = 4, R = 8 → 4 ^ 5 ^ 6 ^ 7 ^ 8 = 8.
long long findXOR(long long l, long long r); // 1 <= l <= r <= 10^9
Input (L, R) | Output | Explanation |
|---|---|---|
(4, 8) | 8 | 4 ^ 5 ^ 6 ^ 7 = 0, then ^ 8 |
(3, 7) | 3 | |
(1, 10) | 11 | 10 mod 4 = 2, so 10 + 1 |
(5, 5) | 5 | |
(1, 1000000000) | 1000000000 | 10⁹ mod 4 = 0 |
(Confirm: 1 ≤ L ≤ R ≤ 10⁹; O(1) per query is expected.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in