PPractick

DSA interview question

Swap Two Numbers Without a Temporary Variable (XOR Swap)

Easy · Algorithms · Topics: bit manipulation

The problem

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.

Function signature

void xorSwap(int& a, int& b);

Test cases

Input (a, b)Output (a, b)Explanation
(5, 7)7 5
(-3, 12)12 -3Works on the bit pattern, signs included
(0, 9)9 0
(4, 4)4 4Equal values in different variables are fine
xorSwap(x, x) with x = 88The same variable must not be zeroed

(Confirm: no temporary variable; must work for negative numbers; swapping a variable with itself must leave it unchanged.)

How interviewers phrase it

Clarifying questions to ask

  1. Integers only? (XOR doesn't apply to floating point.)
  2. Can the two references refer to the same variable?
  3. Is overflow a concern? (It rules out the arithmetic version.)

Follow-ups to expect

  1. "Prove the XOR swap."
  2. "What breaks with aliasing?"
  3. "Why not a = a + b; b = a − b; a = a − b?"
  4. "Is it faster than a temporary?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in