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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code