Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Swap Two Values in Array

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

Your question is Swap Two Values in Array. 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

UT Austin's course scheduling tools sometimes reorder items represented as arrays. Given an integer array and two valid indices, swap the elements at those indices in place and return the modified array.

Formal Specification

Implement swap_elements(nums, i, j):

  • nums is a mutable list of integers.
  • i and j are zero-based indices in nums.
  • Modify nums directly rather than creating a second array.
  • Return the same list after the swap.
  • If i and j are equal, leave the list unchanged.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[k] <= 10^9
  • 0 <= i, j < len(nums)
  • i and j may be equal

Function Signature

def swap_elements(nums, i, j):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output