Quick revision
The short answer
Swapping two numbers without a temporary variable is a math and bits problem: store both values in one variable with a reversible operation, then undo it twice. With arithmetic it is a = a + b; b = a - b; a = a - b, and with XOR it is a = a ^ b; b = a ^ b; a = a ^ b. Both are O(1) time and space, both destroy the value when the two names refer to the same storage, and in real code the temporary variable is clearer and just as fast.
The solution
What it costs
| Swap | Overflow | Same storage twice | Works for doubles and objects |
|---|---|---|---|
| Temporary variable | no risk | works | yes |
| a + b, then subtract | wraps and cancels in Java | destroys the value | no |
| XOR three times | cannot overflow | destroys the value | no, ints and longs only |
What to remember
We swapped two ints without a third variable by storing both values in one of them with a reversible operation and undoing it twice: a + b followed by two subtractions, or three XORs, where a value applied twice cancels. Both take O(1) time and space, the arithmetic version is safe from overflow in Java because the wrap-around cancels, and both destroy the value when the two names are the same storage. The clue to remember is a ban on extra space for numbers, which points to an operation that can be undone.
1What it means to swap two values, and why it needs care
Picture two glasses on a table, one holding milk and one holding juice, and suppose we want the milk in the second glass and the juice in the first. Anyone would fetch a third, empty glass: pour the milk into it, pour the juice into the first glass, then pour the milk from the spare glass into the second. Without the spare glass we would have to pour one drink into the other, and once milk and juice are mixed, nobody can separate them again.
Variables in a program are like those glasses. A variable is a named box that holds one value at a time, and putting a new value in throws the old one away. So swapping a and b normally needs a third variable, the spare glass. This question asks us to swap two int variables without one. It sounds like a magic trick, but it is a small one. Numbers, unlike drinks, can be mixed in a way that can be undone, and that is the whole secret.
Each cell is one int variable. The labels underneath are the variable names.
- a now
- 7
- b now
- 12
- a after
- 12
- b after
- 7
1a holds 7 and b holds 12. After the swap a must hold 12 and b must hold 7, and we may not declare a third variable to help.
What to assume
- Are the values ints, or could they be floating point numbers?
- We assume ints, because the tricks rely on exact whole number arithmetic.
- Is the swap meant to happen inside a method?
- In Java, int arguments are copied into the method, so a method
swap(int a, int b)cannot change the caller's variables; we either swap locals in place or swap two slots of an array.
Let us keep one example. a holds 7 and b holds 12, and afterwards a must hold 12 and b must hold 7. Try it by hand for a moment. If the first line is a = b, then a is 12, but the 7 is gone, and b can never get it back. If the first line is b = a, the 12 is gone instead. Whatever we do first destroys something, unless the first step stores both values in one variable at once. Keep that observation in mind, because the solution grows from it.
A careful candidate asks a few questions first. Are the values ints, or could they be floating point numbers? We assume ints, because the tricks rely on exact whole number arithmetic. Can the two names refer to the same storage, such as a[i] and a[j] when i equals j? That case matters, and we will see what goes wrong. Is the swap meant to happen inside a method? In Java, int arguments are copied into the method, so a method swap(int a, int b) cannot change the caller's variables; we either swap locals in place or swap two slots of an array.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to spot the pattern behind the no temporary rule
When a beginner first reads this question, it can feel like a riddle with no handle to hold. There is no loop to write and no data structure to choose. The natural first try is to shuffle the two assignments around in different orders, and as we just saw by hand, every order loses one value. That is a useful failure, because it tells us what is missing: somewhere to keep both values for a moment.
So let us read the question for clues, one at a time. The first clue is the phrase without using a temporary variable. Underneath, it means without extra space. We have exactly two boxes and must not lose either value, so at some moment one box has to carry information about both numbers.
The second clue is the word numbers. We are swapping values we can do arithmetic on, so we can combine them with an operation such as addition. An operation is reversible, meaning it can be undone, if knowing the result and one of the inputs is enough to recover the other input. Addition is reversible in this sense: if a + b is 19 and b is 12, then a must be 19 - 12 = 7.
These clues point to the math and bits family. Its problems are solved not by a data structure but by a property of numbers or of their binary digits. The idea here is to combine both values into one variable with a reversible operation, then undo it twice, once to recover each original. The rule to carry to other problems is this: when a question forbids extra space for numbers, look for an operation that can be undone, because it lets one variable hold two pieces of information.
There are two good reversible operations. Addition is undone by subtraction. XOR, a bit operation we will meet slowly in a moment, is undone by itself. Other bit tools look related but do not fit. Bit masks store a set of yes or no flags, and shifts multiply or divide by powers of two; neither keeps two independent numbers in one box. Multiplication looks reversible too, since division undoes it, but it breaks when either value is 0, which the follow-up questions explain.
3The honest first attempt, the temporary variable
The first solution anyone writes, and the one we would write in real code, uses the spare glass. Let us not skip it, because it is the standard that the tricks must match, and in an interview it is good to show it first.
Let us run it by hand. tmp = a stores 7 in the spare box. a = b puts 12 into a; the 7 in a is overwritten, but it is safe in tmp. b = tmp puts 7 into b. Three assignments, and the values have changed places.
What does it cost? Three assignments, whatever the values, so the time is O(1), read as constant: it never grows. The space is one extra int, also O(1). It works for every type, ints, doubles and objects alike, and it works even when a and b are the same storage, because copying a value onto itself changes nothing.
So where is the waste we usually look for in a brute force? There is none in time; the tricks also take three steps. The only thing this version uses that the question forbids is the one extra variable. That changes the goal of the next section. We are not trying to be faster; we are trying to keep both values alive inside the two boxes we already have.
4Getting to a swap without a temporary, one observation at a time
Our hand experiment showed that the first step must store both values in one box. Addition does exactly that. After a = a + b, a holds 19, and 19 is not just some number; it is 7 and 12 together, in a form we can take apart, because subtracting either one gives the other.
Now we take it apart, one value at a time. b = a - b computes 19 - 12 = 7, the old a, and stores it in b. At this moment a still holds the sum and b holds the old a. Then a = a - b computes 19 - 7 = 12, the old b. The sum is used up and the values have swapped. At every step one box holds the sum and the other holds one of the originals, and subtracting recovers the missing one.
Now the question a careful beginner asks. What if a + b is too big for an int? Let us try the worst case and see. Take a = Integer.MAX_VALUE, which is 2,147,483,647, and b = 5. The sum does not fit, and in Java an int that goes past its largest value wraps around to the most negative values, like a car's odometer rolling past 999999 to 000000. Our run shows a becoming -2,147,483,644. That looks like a disaster, but watch the next two lines. b = a - b wraps back the other way and gives 2,147,483,647, and a = a - b gives 5. The swap is correct.
Why does the wrap-around cancel? Java defines int arithmetic as arithmetic on a clock of 2 to the power 32 positions. On a clock, going forward by 5 and then back by 5 lands where we started, however many times we passed twelve on the way. The language specification guarantees this behaviour, so the arithmetic swap is safe in Java, though not in languages where overflow is undefined.
The second reversible operation works on bits. A bit is one binary digit, 0 or 1, and every int is stored as 32 bits. In binary 7 is 0111, which is 4 + 2 + 1, and 12 is 1100, which is 8 + 4. XOR, written ^ in Java, compares two numbers bit by bit and writes 1 where the bits differ and 0 where they are the same. So 0111 ^ 1100 is 1011, which is 11.
XOR is undone by itself, because of two small facts. Any number XOR itself is 0, since every bit matches. Any number XOR 0 is itself, since nothing differs from 0 but the 1s. And the order of the operands does not matter. So (7 ^ 12) ^ 12 is 7 ^ (12 ^ 12), which is 7 ^ 0, which is 7. Applying a value twice cancels it, the way flipping a light switch twice leaves the light as it was.
So the XOR swap follows the same shape as the arithmetic one. x = x ^ y stores the bits where the values differ. y = x ^ y cancels the old y out of that, leaving the old x. x = x ^ y cancels the old x out, leaving the old y. XOR never overflows, because it never carries a bit from one place to the next, which is why many people prefer it.
5Watching both swaps on 7 and 12
The picture plays both swaps. The two cells are the two variables, with their names underneath, and the panel shows their values and the next line of code. The first four frames are the arithmetic swap on a and b; the last four are the XOR swap on x and y, with each value also written in four binary digits.
Frames 1 to 4 run the arithmetic swap; frames 5 to 8 run the XOR swap. The panel shows each value, and for XOR its four lowest bits.
- a
- 7
- b
- 12
- next line
- a = a + b
1The arithmetic swap starts with a = 7 and b = 12.
- a
- 19, which is 7 + 12
- b
- 12
- next line
- b = a - b
2a = a + b puts the sum 19 into a. The old 7 is gone from view, but it is hidden inside 19, because 19 - 12 gives it back.
- a
- 19
- b
- 7, the old a
- next line
- a = a - b
3b = a - b computes 19 - 12 = 7 and stores it in b. b now holds the old a, and a still holds the sum.
- a
- 12
- b
- 7
4a = a - b computes 19 - 7 = 12 and stores it in a. The sum is used up, and the two values have changed places.
- x
- 7 = 0111
- y
- 12 = 1100
- next line
- x = x ^ y
5The XOR swap starts again from x = 7 and y = 12. In four binary digits, 7 is 0111 and 12 is 1100.
- x
- 11 = 1011
- y
- 12 = 1100
- next line
- y = x ^ y
6x = x ^ y puts a 1 wherever the two numbers differ. 0111 and 1100 differ in three places, so x becomes 1011, which is 11.
- x
- 11 = 1011
- y
- 7 = 0111
- next line
- x = x ^ y
7y = x ^ y is 1011 ^ 1100 = 0111, which is 7. The 12 inside x cancels the 12 in y, leaving the old x.
- x
- 12 = 1100
- y
- 7 = 0111
8x = x ^ y is 1011 ^ 0111 = 1100, which is 12. This time the 7 cancels, and the swap is complete.
Let us read the important frames back. In the second frame a holds 19. Nothing has been lost, even though 7 appears nowhere, because 19 together with the 12 in b is enough to rebuild it. That is the moment that answers the riddle: one box holds both values.
In the sixth frame x holds 1011, which is 11. Look at the bits. Wherever 7 and 12 differ, 1011 has a 1. In the seventh frame XOR with y's 1100 flips exactly those bits back, giving 0111. Check the eighth frame yourself: 1011 ^ 0111 has a 1 wherever they differ, which gives 1100, or 12.
6The complete Java program
Here is the whole program. main swaps two locals with arithmetic and two with XOR, swaps Integer.MAX_VALUE with 5 to show the overflow cancelling, and then shows the danger case on array slots, first without a guard and then with one. Each printed line has its result as a comment.
Let us read main in the order it runs. The first block is the arithmetic swap we traced, and it prints a=12 b=7. The second block is the XOR swap, and it prints x=12 y=7. The third block uses Integer.MAX_VALUE and 5. The sum overflows, the two subtractions overflow back, and it prints p=5 q=2147483647.
The last part is the reason the two methods exist. unguardedXorSwap(arr, 0, 0) is called with the same index twice, which happens easily inside a sorting or shuffling routine that sometimes swaps an element with itself. Both names then mean the same cell, the first line computes 3 ^ 3 = 0, and the program prints 0. The value is destroyed.
xorSwap has one extra line at the top, if (i == j) return, which handles that case by doing nothing, since swapping a slot with itself should change nothing. The program then calls xorSwap(arr2, 0, 0), which leaves the array alone, and xorSwap(arr2, 0, 1), which swaps 3 and 9, so it prints 9 3.
7How much it costs, and the cases at the edges
Every version does three operations whatever the values, so the time is O(1). The temporary version uses one extra int and the tricks use none, so the space is O(1) for all of them. In practice the tricks save nothing measurable. The Java compiler and the JIT, the part of the Java runtime that turns hot code into machine instructions, keep local variables in processor registers, so the temporary usually costs nothing, while the tricks make each step depend on the previous one.
The edge case that matters most is aliasing, which means two names referring to the same storage. The picture shows what the XOR swap does then. The arithmetic version fails the same way: a[i] = a[i] + a[i] gives 6, then a[i] - a[i] gives 0, and the value is lost.
We call the unguarded swap with i = 0 and j = 0, so a[i] and a[j] are the same cell.
- a[i]
- 3
- a[j]
- 3, the same cell
1The array is {3, 9}. Both i and j are 0, so a[i] and a[j] name the very same cell, the one holding 3.
- a[i]
- 0
- 3 ^ 3
- 0
2a[i] ^= a[j] is now 3 ^ 3, and any number XOR itself is 0. The 3 is destroyed, with no copy left anywhere.
- a[i]
- 0
- 0 ^ 0
- 0
3a[j] ^= a[i] is 0 ^ 0, which is still 0. There is nothing left to recover the 3 from.
- printed
- 0
- should be
- 3
4The third line gives 0 again. The program prints 0 where the guarded swap, which returns at once when i == j, would leave 3.
| Swap | Overflow | Same storage twice | Works for doubles and objects |
|---|---|---|---|
| Temporary variable | no risk | works | yes |
| a + b, then subtract | wraps and cancels in Java | destroys the value | no |
| XOR three times | cannot overflow | destroys the value | no, ints and longs only |
The other edge cases are kinder. Equal values in two different variables swap correctly, because x ^ x is 0 only when both names are the same box; with two boxes holding 5, x becomes 0, y becomes 0 ^ 5 = 5, and x becomes 0 ^ 5 = 5. Negative numbers work with both tricks, since they are just other bit patterns. Floating point numbers do not, because rounding in a + b can lose the small value forever.
So in an interview we show the tricks, explain why they work and where they break, and then say plainly that in real code we would use the temporary variable, because it is clearer and just as fast.
8Follow-up questions
Can you swap with multiplication and division instead?
In principle the shape is the same: a = a * b, then b = a / b, then a = a / b. With 7 and 12 the product is 84, then 84 / 12 = 7 and 84 / 7 = 12. But it fails as soon as either value is 0, because the product is 0 and the other value is lost, and the division then throws an ArithmeticException. The product also overflows far sooner than a sum, and unlike addition, an overflowed product is not undone by division. So multiplication is not a safe reversible operation here.
Why does XOR appear in the single number problem as well?
In that problem every value in an array appears twice except one, and we must find the one. If we XOR all the elements together, each pair cancels, because x ^ x is 0, and the lone value is left, because x ^ 0 is x. The order does not matter, so the pairs need not sit together. It is exactly the cancelling property that makes the XOR swap work, and it gives an O(n) time, O(1) space answer.
Can you write a Java method swap(int a, int b) that swaps the caller's variables?
No. Java passes every argument by value, which means the method receives copies of the two ints. Swapping the copies inside the method has no effect on the caller's variables. To swap through a method we pass something that holds the values, such as an int array with two indexes, as our xorSwap does, or we return the swapped pair, for example as a small record, and let the caller assign it.
9Conclusion
We swapped two ints without a third variable by storing both values in one of them with a reversible operation and undoing it twice: a + b followed by two subtractions, or three XORs, where a value applied twice cancels. Both take O(1) time and space, the arithmetic version is safe from overflow in Java because the wrap-around cancels, and both destroy the value when the two names are the same storage. The clue to remember is a ban on extra space for numbers, which points to an operation that can be undone.
Open with
I will assume two int variables and that I may change them in place. The normal swap uses a temporary, and in production code that is what I would write, because it is clear, works for any type, and is just as fast.
Then, if they want more
Without a temporary, I need one variable to hold both values for a moment, using an operation I can undo. With arithmetic, a = a + b stores the sum, b = a - b recovers the old a, and a = a - b recovers the old b.
In Java this is safe even if the sum overflows, because int arithmetic wraps around modulo 2 to the 32, and the subtractions wrap back.
With XOR, a = a ^ b stores the bits where they differ, and since x ^ x is 0 and x ^ 0 is x, b = a ^ b gives the old a and a = a ^ b gives the old b; XOR cannot overflow. Both are O(1) time and space.
The important edge case is aliasing: if both names refer to the same storage, such as a[i] and a[j] with i equal to j, the first step makes the value 0 and it is lost, so a swap helper should return early when i equals j.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 24 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Swap two numbers without using a temporary variable.": https://scrivio-interview-library.netlify.app/data-structures/solutions/swap-two-numbers-without-using-a-temporary-variable-b1e51c/