Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Swap Registers Without Temp

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

Your question is Swap Registers Without Temp. 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 low-level component of IBS Software's iFly platform stores integer values in a register bank represented by a Python list. Swap the values at two specified register positions in place, without using a temporary variable, a third register, tuple unpacking, or another data structure for storage.

Use the XOR-swap technique. If both positions refer to the same register, leave its value unchanged. The function must return the modified register bank.

Formal Specification

Implement swap_registers(registers, first, second):

  • registers is a list of integers.
  • first and second are valid, zero-based register indices.
  • Return the same list object after swapping registers[first] and registers[second].
  • The implementation must use constant auxiliary space and must not store either register value in a third variable.

Constraints

  • 1 <= len(registers) <= 10^5
  • 0 <= first, second < len(registers)
  • registers[k] is an integer
  • first and second may be equal
  • Do not use a temporary variable, tuple unpacking, or auxiliary collection

Function Signature

def swap_registers(registers, first, second):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output