← Back

25. Swap Without Temporary Variable

Medium

📝 Problem

Given two numbers, Swap those two numbers without using temporary variable.

Input Format:
Accept two integer values as input
Output Format:
Print the output as follows:
num1=respective value
num2=respective value
Constraints:
1 ≤ num1, num2 ≤ 10^9
Sample Input 1:
23 26
Sample Output 1:
num1=26
num2=23
Sample Input 2:
10
20
Sample Output 2:
num1=20
num2=10
🎯 Advanced Swapping: All Techniques Without Temporary Variables!

The Challenge

In the previous question (#24), we used a temporary variable. But what if we told you there are clever mathematical and bitwise tricks to swap without using extra memory? Welcome to the world of space-efficient algorithms!

💡 Why This Question is Special
This problem introduces XOR bitwise operation - one of the most elegant tricks in programming. It's not just about swapping; it's about understanding how computers work at the binary level!

1️⃣ Method 1: XOR Bitwise Swap (Our Solution) ⭐

📌 The XOR Magic:
long long a = 23, b = 26;

a = a ^ b;  // Step 1: a = 23 ^ 26 = 13
b = a ^ b;  // Step 2: b = 13 ^ 26 = 23 (original a!)
a = a ^ b;  // Step 3: a = 13 ^ 23 = 26 (original b!)

// Result: a=26, b=23 ✓ Swapped!

🔍 Understanding XOR (^) Operator

What is XOR (Exclusive OR)?

XOR returns 1 when bits are different, 0 when they're the same:

📌 XOR Truth Table:
a    b    a^b
0    0     0
0    1     1
1    0     1
1    1     0

// Example with numbers:
23 in binary: 10111
26 in binary: 11010
              -----
23 ^ 26     : 01101 = 13

🧠 Why XOR Swap Works: The Math Behind It

📌 Mathematical Proof:
// Key Properties of XOR:
// 1. a ^ a = 0 (same number cancels out)
// 2. a ^ 0 = a (XOR with 0 keeps the number)
// 3. a ^ b ^ b = a (b cancels itself)

// Starting values: a=23, b=26

// Step 1: a = a ^ b
a = 23 ^ 26  // a now holds (23 ^ 26)

// Step 2: b = a ^ b = (23 ^ 26) ^ 26
//         = 23 ^ (26 ^ 26)
//         = 23 ^ 0
//         = 23 ✓ (original a!)

// Step 3: a = a ^ b = (23 ^ 26) ^ 23
//         = (23 ^ 23) ^ 26
//         = 0 ^ 26
//         = 26 ✓ (original b!)
🎯 The Beauty: XOR is its own inverse! XORing twice with the same value brings you back to the original. This property makes the swap possible!

2️⃣ Method 2: Arithmetic Swap (Addition/Subtraction)

📌 Using Math:
long long a = 23, b = 26;

a = a + b;  // a = 23 + 26 = 49
b = a - b;  // b = 49 - 26 = 23 (original a!)
a = a - b;  // a = 49 - 23 = 26 (original b!)

// Result: a=26, b=23 ✓ Swapped!
⚠️ Arithmetic Swap Limitation
Overflow Risk! If a + b exceeds the maximum value of the data type (e.g., INT_MAX), the result wraps around and corrupts the values. XOR doesn't have this problem!

3️⃣ Method 3: Multiplication/Division Swap

📌 Using Multiplication:
long long a = 23, b = 26;

a = a * b;  // a = 23 * 26 = 598
b = a / b;  // b = 598 / 26 = 23 (original a!)
a = a / b;  // a = 598 / 23 = 26 (original b!)

// Result: a=26, b=23 ✓ Swapped!
⚠️ Multiplication Swap Limitations
Two Major Issues:
  • ❌ Fails if either number is 0 (division by zero!)
  • ❌ Overflow risk with large numbers (product can exceed limits)

📊 Comparison of All Swapping Methods

Method Extra Space Overflow Risk Works with 0 Readability Best For
Temp Variable ❌ Needs temp ✅ No risk ✅ Yes ⭐⭐⭐⭐⭐ General use
XOR Bitwise ✅ No extra ✅ No risk ✅ Yes ⭐⭐⭐ Integers only
Arithmetic (+/-) ✅ No extra ⚠️ Possible ✅ Yes ⭐⭐⭐⭐ Small numbers
Multiply/Divide ✅ No extra ⚠️ High risk ❌ Fails! ⭐⭐ Rarely used

4️⃣ When to Use Each Method?

💡 Professional Recommendations
Use Temp Variable When:
  • ✅ Writing production code (clarity matters!)
  • ✅ Working with any data type (floats, objects, etc.)
  • ✅ Code readability is important
Use XOR When:
  • ✅ Memory is extremely limited
  • ✅ Working with integers only
  • ✅ Showing off in interviews 😎
  • ✅ Learning bitwise operations

🚀 Real-World Applications of XOR

XOR isn't just for swapping - it's used in:

  • Cryptography - Simple encryption schemes
  • Error Detection - Parity bits, checksums
  • Data Structures - XOR linked lists (doubly linked with single pointer!)
  • Graphics - Fast color inverting, sprite masking
  • Puzzle Algorithms - Finding unique elements in arrays
  • Network Protocols - RAID storage systems
📌 Cool XOR Trick - Find Missing Number:
// Array has numbers 1-5, but one is missing
int arr[] = {1, 2, 4, 5};  // 3 is missing

int xor_all = 1 ^ 2 ^ 3 ^ 4 ^ 5;  // XOR of complete set
int xor_arr = 1 ^ 2 ^ 4 ^ 5;      // XOR of array
int missing = xor_all ^ xor_arr;    // Result: 3!

Mastering XOR opens doors to elegant solutions for complex problems!

💻 Solution Code
#include <iostream>

using namespace std;

int main() {
    long long a, b;
    cin >> a >> b;
    
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    
    cout << "num1=" << a << "\nnum2=" << b;
    return 0;
}