Swap two integers without a temporary variable

Quick Overview

Swap the values of two integers without storing either one in a temporary variable, then return them as a tuple in swapped order. It tests whether you can recover each value from a combined one, and whether you know the overflow and aliasing pitfalls of such tricks in fixed-width languages.

Swap two integers without a temporary variable

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Write a function that swaps the values of two integers `a` and `b` without using a temporary variable. Return the swapped values as a tuple `(b, a)`: the original `b` first and the original `a` second. ### Function Signature ```python def swap_numbers(a: int, b: int) -> tuple[int, int]: ``` ### Rules - Do not store either value in a third variable at any point during the swap. - Return a two-element tuple whose first element is the original `b` and whose second element is the original `a`. ### Constraints - `-10^4 <= a, b <= 10^4` ### Examples ```text Input: a = 3, b = 5 Output: (5, 3) ``` After the swap `a` holds 5 and `b` holds 3, so the tuple lists 5 first. ```text Input: a = -10, b = 20 Output: (20, -10) ``` Negative values swap the same way as positive ones: the original `b` (20) comes first and the original `a` (-10) second. ```text Input: a = 7, b = 7 Output: (7, 7) ``` When both values are equal, swapping leaves the same pair.

Overview: Swap the values of two integers without storing either one in a temporary variable, then return them as a tuple in swapped order. It tests whether you can recover each value from a combined one, and whether you know the overflow and aliasing pitfalls of such tricks in fixed-width languages.

Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Write a function that swaps the values of two integers a and b without using a temporary variable. Return the swapped values as a tuple (b, a): the original b first and the original a second.

Function Signature

def swap_numbers(a: int, b: int) -> tuple[int, int]:

Rules

  • Do not store either value in a third variable at any point during the swap.
  • Return a two-element tuple whose first element is the original b and whose second element is the original a .

Constraints

  • -10^4 <= a, b <= 10^4

Examples

Input: a = 3, b = 5
Output: (5, 3)

After the swap a holds 5 and b holds 3, so the tuple lists 5 first.

Input: a = -10, b = 20
Output: (20, -10)

Negative values swap the same way as positive ones: the original b (20) comes first and the original a (-10) second.

Input: a = 7, b = 7
Output: (7, 7)

When both values are equal, swapping leaves the same pair.