Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Two Number Swap

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

Your question is Two Number Swap. 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

H&R Block's tax calculation code may need to exchange two intermediate integer values. Implement a function that swaps two integers without using a third variable or temporary container.

Formal Specification

Define swap_numbers(a, b), where a and b are integers. Return a two-element tuple containing the values in swapped order: (b, a). The implementation must use only the variables a and b for the swap, aside from the function's return value. Do not use tuple unpacking, lists, dictionaries, or another temporary variable.

Use arithmetic operations to perform the swap. Python integers do not overflow, so the arithmetic approach is safe for all values within the stated constraints.

Constraints

  • -10^9 <= a, b <= 10^9
  • a and b are integers
  • Do not use a third variable or temporary data structure
  • Return the swapped values as a two-element tuple

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