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:
a = a ^ bβ Nowaholds (a β b)b = a ^ bβ Nowbbecomes (a β b) β b = aa = a ^ bβ Nowabecomes (a β b) β a = b
- After the three XOR operations,
aandbare swapped.
π§© Key Formulaβ
a = a ^ b;
b = a ^ b;
a = a ^ b;
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(1) |
| Space | O(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β
| Method | Extra Space | Temp Var Used? |
|---|---|---|
| Temp variable | O(1) | Yes |
| Arithmetic method | O(1) | No |
| Bit manipulation β | O(1) | No |
π Related Problemsβ
- Swap values in an array without using extra space
- XOR properties in finding missing number
- Bitwise tricks in interview puzzles
π¬