Skip to main content

Swap Two Numbers

Problem Statement:​

  • Example:


βœ… Solution: Bit Manipulation (XOR Swap)​

class Solution {
public:
void swapNumbers(int &a, int &b) {
if (a != b) {
a = a ^ b; // Step 1
b = a ^ b; // Step 2 (a ^ b) ^ b = a
a = a ^ b; // Step 3 (a ^ b) ^ a = b
}
}
};


πŸ“ How It Works​

  • This method uses XOR to swap two variables without using a temporary variable.
  • Step-by-step:
    1. a = a ^ b β€” Now a holds (a βŠ• b)
    2. b = a ^ b β€” Now b becomes (a βŠ• b) βŠ• b = a
    3. a = a ^ b β€” Now a becomes (a βŠ• b) βŠ• a = b
  • After the three XOR operations, a and b are swapped.

🧩 Key Formula​

a = a ^ b;
b = a ^ b;
a = a ^ b;


⏱️ Time & Space Complexity​

MetricValue
TimeO(1)
SpaceO(1)

⚠️ Edge Cases​

  • Must check a != b. If both refer to the same memory address, result will become zero.
  • Doesn’t work safely for pointers to the same variable.

πŸ’‘ Other Approaches​

MethodExtra SpaceTemp Var Used?
Temp variableO(1)Yes
Arithmetic methodO(1)No
Bit manipulation βœ…O(1)No

  • Swap values in an array without using extra space
  • XOR properties in finding missing number
  • Bitwise tricks in interview puzzles

πŸ’¬

Discussion & Doubts