Swap Two Variables - Problem

Write a program to swap two variables without using a third variable.

You are given two integers and need to exchange their values without creating any additional temporary variable. There are multiple mathematical and bitwise approaches to achieve this.

Your function should take two integers as input and return them in swapped order as an array [b, a] where the original values were a and b.

Input & Output

Example 1 — Basic Swap
$ Input: a = 5, b = 3
Output: [3, 5]
💡 Note: The values are swapped: original a=5 becomes second element, original b=3 becomes first element
Example 2 — Negative Numbers
$ Input: a = -2, b = 7
Output: [7, -2]
💡 Note: Works with negative numbers: original a=-2 becomes second, original b=7 becomes first
Example 3 — Same Values
$ Input: a = 4, b = 4
Output: [4, 4]
💡 Note: When both values are same, swapping still works and result is [4, 4]

Constraints

  • -109 ≤ a, b ≤ 109
  • Must not use any temporary variables
  • Return format: [b, a] where original inputs were a and b

Visualization

Tap to expand
INPUTALGORITHMRESULTa5b3Two variables to swapwithout temporary variable1a = a ⊕ bStore XOR result2b = a ⊕ bExtract original a3a = a ⊕ bExtract original bXOR properties:X ⊕ X = 0, X ⊕ 0 = X3(was b)5(was a)[3, 5]Values successfullyswapped!Key Insight:XOR operation acts like a reversible encoding - applying it twice with the samevalue gets you back to the original, making it perfect for swapping without extra memory!TutorialsPoint - Swap Two Variables | XOR Bit Manipulation
Asked in
Microsoft 25 Amazon 20 Google 15
25.0K Views
Medium Frequency
~10 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen