Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

At Most One Swap to Sort

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

Your question is At Most One Swap to Sort. 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

HERE Technologies uses ordered location data in workflows such as HERE Map Content validation. Given an array of integers, determine whether it can be sorted in nondecreasing order using at most one swap of two elements.

A swap exchanges the values at any two distinct indices. The array may also require no change. Return True if the condition can be satisfied, otherwise return False.

Formal Specification

Implement can_be_sorted_by_one_swap(nums).

  • Input: nums, a list of integers.
  • Output: A boolean indicating whether zero or one arbitrary swap can make nums nondecreasing.
  • The function should not permanently modify nums.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Equal values are allowed
  • The swap may involve any two distinct indices

Function Signature

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