Last Updated: June 7, 2026
Swapping two values is a basic building block in real code. Sorting algorithms swap elements, in-place array rearrangements swap positions, and many math routines rely on exchanging two variables.
You return a new array with the positions flipped. If a is 5 and b is 7, the answer is [7, 5]. There are two well-known ways to do the swap, and each shows something about how variables hold values.
-2^31 <= a, b <= 2^31 - 1 → Both inputs use the full 32-bit signed integer range. This matters for the arithmetic swap in Approach 2, where adding a and b can exceed the maximum and overflow. The temporary-variable method has no such risk.4 and 4 simply returns [4, 4], and swapping 0 with anything works without special cases.The moment you copy b into a, the original value of a is gone, so you can no longer place it into b.
A temporary variable gives you somewhere to hold one value before it is overwritten. Save a, move b into a, then move the saved value into b.
a in a temporary variable temp.b to a.temp to b.[a, b], which now holds the swapped values.Input:
Save a into temp so it is not lost, then copy b into a:
Finally, copy temp into b. The swapped result is returned as an array:
temp, is used.The temporary variable is clear and safe, but it does use one extra slot of memory. Can we swap two values without any helper variable at all?
Arithmetic can replace the temporary variable: encode both values into one variable, then peel them back apart.
Store the sum in a with a = a + b. Now a holds enough to recover either original value. Subtract the current b to get the original a and place it in b with b = a - b. Then subtract the new b from the sum to recover the original b with a = a - b. Return them as [a, b].
The XOR-swap variant works the same way for integers: a ^= b; b ^= a; a ^= b. It avoids the overflow concern of addition, since XOR never grows beyond the operands. The arithmetic version can overflow when a + b exceeds the 32-bit signed range, so the temporary-variable method from Approach 1 remains the safer general choice.
a = a + b. Now a holds the sum of both original values.b = a - b. This subtracts the original b from the sum, leaving the original a in b.a = a - b. This subtracts the new b (original a) from the sum, leaving the original b in a.[a, b], which now holds the swapped values.Input:
After a = a + b, the variable a holds the sum 12, while b is still 7:
After b = a - b (which is 12 - 7 = 5), b now holds the original a. Then a = a - b (which is 12 - 5 = 7) leaves the original b in a. The swapped result is returned: