Swapping two variables may look like a beginner-level problem, but many candidates still fail this question during coding interviews cause they use a third variable shows a lack of understanding of in-place operations and space optimization, which interviewers pay close attention to.
In this tutorial, you will learn How you can do a swap of two variables without using a third variable, understand the core Arithmatic Operation behind it and visualize the process with a step by step animation.
We will solve this problem using C++, Java, Python, and JavaScript, so you can clearly see how the same algorithm works across different programming languages.
Swap Two Variables without using a third variable
Let’s understand the algorithm first.
Algorithm Steps:
- Store the sum of both variables in the first variable
a = a + b - Subtract the new value of
bfromato get the original value ofab = a - b - Subtract the new value of
bfromato get the original value ofba = a - b
✔ No extra space used
✔ Time Complexity: O(1)
✔ Space Complexity: O(1)

Programming Languange
To solve this problem , we have used below programming language
- C++
- Java
- Python
- JavaScript
Each implementation follows the same algorithm, helping you understand how logic remains constant while syntax changes.
#include <iostream>
using namespace std;
int main() {
int a = 20;
int b = 10;
a = a + b;
b = a - b;
a = a - b;
cout << "a = " << a << " and b = " << b << endl;
return 0;
}public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 20;
int b = 10;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a + " and b = " + b);
}
}
a = 20
b = 10
a = a + b
b = a - b
a = a - b
print("a =", a, "and b =", b)let a = 20;
let b = 10;
a = a + b;
b = a - b;
a = a - b;
console.log("a = " + a + " and b = " + b);Output

Conclusion
Swapping two variables without using a third variable is a small but powerful DSA concept that tests your understanding of logic, space optimization, and in-place operations. By learning the algorithm, visualizing it through animations, and practicing the solution in multiple programming languages, you build strong fundamentals that interviewers look for.

