Swap Two Numbers

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given two integers a and b, return them swapped — [b, a] — without using a third variable to hold either value temporarily. XOR gives a way to swap in place: a ^= b changes a into a ^ b; b ^= a then changes b into b ^ (a ^ b), which simplifies to the original a; and a final a ^= b changes a into (a ^ b) ^ (original a), which simplifies to the original b. Three XOR operations, two variables, nothing extra needed.

Test Case 1:

Input:a = 5, b = 10
Output:[10, 5]
Explanation:Straightforward swap of two distinct values.

Test Case 2:

Input:a = -3, b = 8
Output:[8, -3]
Explanation:Works the same way regardless of sign.

Test Case 3:

Input:a = 5, b = 5
Output:[5, 5]
Explanation:Swapping equal values leaves them unchanged — a and b are separate variables holding the same value, not aliases of one memory location, so the XOR trick handles this correctly too.

Constraints

  • -2³¹ ≤ a, b ≤ 2³¹ − 1
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

Approach & Solutions

Using a Temporary Variable

Good

Hold one value aside in a third variable while the assignment happens, then hand it back into the other slot.

TimeO(1)
SpaceO(1)
1class Solution { 2 public int[] swapTwoNumbers(int a, int b) { 3 int temp = a; 4 a = b; 5 b = temp; 6 return new int[]{a, b}; 7 } 8}

Optimal — XOR Swap (No Temporary Variable)

Optimal

a ^= b changes a into a ^ b. b ^= a then changes b into b ^ (a ^ b), which simplifies to the original a, since XOR-ing b with itself cancels it. A final a ^= b changes a into (a ^ b) ^ (original a), which simplifies to the original b. Three XOR operations, two variables, nothing extra needed.

TimeO(1)
SpaceO(1)
1class Solution { 2 public int[] swapTwoNumbers(int a, int b) { 3 a = a ^ b; 4 b = b ^ a; 5 a = a ^ b; 6 return new int[]{a, b}; 7 } 8}

Related Problems