Category: Easy | Concepts used: Temporary registers, arithmetic swapping, bitwise XOR operations
Problem Statement
Given two integers a and b, swap their values โ so a gets bโs original value and b gets aโs original value.
Input : a = 5, b = 10 Output: a = 10, b = 5
Input : a = -3, b = 7 Output: a = 7, b = -3
Examples (with edge scenarios)
| # | a (before) | b (before) | a (after) | b (after) | Note |
|---|---|---|---|---|---|
| 1 | 5 | 10 | 10 | 5 | Standard positive values |
| 2 | 0 | 9 | 9 | 0 | Swapping with zero |
| 3 | -3 | 7 | 7 | -3 | Swapping with negative numbers |
| 4 | 4 | 4 | 4 | 4 | Swapping identical values |
โ ๏ธ Common Beginner Mistake
Mistake Impact Fix Overwriting abefore backing it upa = b; b = a;leaves both variables holdingbโs original valueUse a tempvariable to cacheabefore overwritingRelying on arithmetic swap for arbitrary values Risk of integer overflow when a + bexceeds2,147,483,647Use the temporary variable approach in production code
Before You Code: Clarify the Contract
Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.
Analogy: The Juice Cup Switch
Imagine you have two glasses filled with different colored juices:
- Glass A contains Red Juice.
- Glass B contains Blue Juice.
You want to swap the contents so Glass A has Blue Juice and Glass B has Red Juice:
- You cannot pour Red directly into Blue because they will mix and get ruined.
- Instead, you introduce an empty Glass Temp.
- You pour Red from Glass A into Glass Temp. Now Glass A is empty, and Temp has Red.
- You pour Blue from Glass B into Glass A. Now Glass B is empty, and Glass A has Blue.
- You pour Red from Glass Temp into Glass B. Now both glasses are successfully swapped!
Solution 1 โ Using a Temp Variable (Simple & Safe)
This is the standard, production-ready solution.
Intuition
By using an auxiliary variable temp, we hold the value of a in a separate memory register, allowing us to safely overwrite a with b and then write the cached value into b.
public class SwapWithTemp {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Before: a=" + a + ", b=" + b);
int temp = a; // Step 1: Copy a's original value to temp
a = b; // Step 2: Overwrite a with b's value
b = temp; // Step 3: Copy the original a from temp to b
System.out.println("After: a=" + a + ", b=" + b);
}
}
Output:
Before: a=5, b=10
After: a=10, b=5
Solution 2 โ Using Arithmetic, No Temp Variable
This approach uses arithmetic addition and subtraction to track differences.
Intuition
By combining the values into a total sum, we use the sum as a memory buffer. We can retrieve the original variables by subtracting individual components.
public class SwapWithArithmetic {
public static void main(String[] args) {
int a = 5, b = 10;
a = a + b; // a becomes the sum of both (5 + 10 = 15)
b = a - b; // b becomes original a (15 - 10 = 5)
a = a - b; // a becomes original b (15 - 5 = 10)
System.out.println("After: a=" + a + ", b=" + b);
}
}
Note on Overflow: While Java allows integer overflows silently (wrapping around), large numbers can still result in arithmetic anomalies on other systems.
Solution 3 โ Using Bitwise XOR (^), No Temp Variable, No Overflow
This approach performs swapping using XOR bitwise operations.
Intuition
The XOR operator has two key properties:
x ^ x = 0(XOR-ing a value with itself cancels it out)x ^ 0 = x(XOR-ing a value with zero returns the value)
By mixing the bits of a and b together using a = a ^ b, we can extract the original values selectively.
public class SwapWithXOR {
public static void main(String[] args) {
int a = 5, b = 10;
a = a ^ b; // a becomes the XOR combination
b = a ^ b; // b becomes the original a (XOR-canceling out b)
a = a ^ b; // a becomes the original b (XOR-canceling out the new b)
System.out.println("After: a=" + a + ", b=" + b);
}
}
Dry Run (a = 5, b = 10 in binary)
a = 0101 (5)
b = 1010 (10)
Step 1: a = a ^ b = 0101 ^ 1010 = 1111 (15)
Step 2: b = a ^ b = 1111 ^ 1010 = 0101 (5) -> b now holds the original a!
Step 3: a = a ^ b = 1111 ^ 0101 = 1010 (10) -> a now holds the original b!
๐ Visual Sequence Diagram
sequenceDiagram
participant a as Variable A
participant b as Variable B
participant temp as Temp Variable
Note over a, b: Before Swap: a = 5, b = 10
a->>temp: Step 1: Copy value of 'a' into 'temp' (temp = 5)
b->>a: Step 2: Copy value of 'b' into 'a' (a = 10)
temp->>b: Step 3: Copy value of 'temp' into 'b' (b = 5)
Note over a, b: After Swap: a = 10, b = 5
Interviewer Insights
This question determines whether you understand low-level execution trade-offs and code safety.
Follow-up questions you might get:
- โWhat is the self-swap gotcha in Solution 3?โ โ If
aandbrefer to the same memory location (e.g., swappingarr[i]witharr[j]wheni == j):
This destroys the value! This is why XOR swapping is risky inside sorting loops unless guarded bya = a ^ a; // a becomes 0 a = a ^ a; // a remains 0 a = a ^ a; // a remains 0if (i != j). - โWhich solution is preferred in production code?โ โ Solution 1 (Temp Variable). Modern CPU compilers optimize temporary variables into quick register swaps. It is also completely type-safe and handles reference variables, objects, and strings, whereas arithmetic and XOR swaps only support primitive numbers.
Quick Recap
| Approach | Memory Overhead | Type Compatibility | Risks | Interview Signal |
|---|---|---|---|---|
| Temp Variable | Minor (1 variable) | All Types (Objects, Strings, Primitives) | None | Standard, highly readable, production-grade |
| Arithmetic | None | Numbers Only | Integer Overflow | Demonstrates mathematical puzzle-solving |
| Bitwise XOR | None | Integers Only | Destroys data on self-swap | Demonstrates low-level binary register manipulation |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed