Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Swap Integers In Place
00:00
5 left

Swap Integers In Place

EasyPython

Problem

Oracle Cloud Infrastructure code may need to exchange two integer state values during an update. Implement a function that swaps two integers in place without declaring an explicit temporary variable.

Because Python integers are immutable and passed by object reference, the function should return the two values in swapped order. The restriction applies to the implementation: do not use a third named variable, arithmetic storage variable, or a library swap utility.

Formal Specification

Implement swap_in_place(a, b), where a and b are integers. Return a two-element tuple (b, a), representing the values after the swap. The inputs may be positive, negative, or zero.

Constraints

  • a and b are integers.
  • -10^18 <= a, b <= 10^18.
  • Do not declare an explicit temporary variable.
  • Use constant auxiliary space.

Function Signature

def swap_in_place(a, b):
Interviewer

Your question is Swap Integers In Place. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.