Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Swap Two Numbers Without Built-in

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Swap Two Numbers Without Built-in. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

A Manheim vehicle-listing workflow sometimes needs to exchange two integer state values, such as source and destination positions. Implement the swap without using a temporary variable, Python tuple unpacking, or any built-in swap function.

Write a function that accepts two integers and returns them in reversed order. The input values may be positive, negative, or zero, and the function must preserve their exact values.

Formal Specification

  • Input: Two integers a and b.
  • Output: A two-element list [b, a], produced without a third variable or tuple unpacking.
  • Do not use a built-in swap operation.
  • Do not convert the values to strings or use an auxiliary collection to hold the originals.

You may use arithmetic operations. Python integers have arbitrary precision, so integer overflow does not need to be handled.

Constraints

  • -10^9 <= a, b <= 10^9
  • The two inputs may be equal
  • Do not use a temporary variable
  • Do not use tuple unpacking or a built-in swap operation
  • Use O(1) extra space

Function Signature

def swap_numbers(a, b):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output