DSA interview question
An embedded controller with only a few registers needs to swap two integer values in place without a spare variable. The XOR swap does it with three XORs, using the facts that x ^ x = 0 and x ^ 0 = x. It's a classic interview question because of the reasoning it requires and one sharp edge: if both references point to the same variable, the first XOR zeroes it. The arithmetic version (a = a + b; b = a − b; a = a − b) has an overflow problem instead.
Example: a = 5, b = 7 → a = 7, b = 5.
void xorSwap(int& a, int& b);
Input (a, b) | Output (a, b) | Explanation |
|---|---|---|
(5, 7) | 7 5 | |
(-3, 12) | 12 -3 | Works on the bit pattern, signs included |
(0, 9) | 9 0 | |
(4, 4) | 4 4 | Equal values in different variables are fine |
xorSwap(x, x) with x = 8 | 8 | The same variable must not be zeroed |
(Confirm: no temporary variable; must work for negative numbers; swapping a variable with itself must leave it unchanged.)
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