FunctionRacerProblemsRace

Sortable With One Swap

EasySorting and searchingPython, JavaScript, TypeScript, Java, C++

Return True if nums is already in non-decreasing order, or if swapping the items at two positions (one single swap) would put it in non-decreasing order. Otherwise return False.

Repeats are allowed: [1, 3, 2, 2] gives True because swapping the 3 with the last 2 gives [1, 2, 2, 3]. An empty list and a one-item list are already sorted. Do not change nums.

Example 1

nums [1,5,3,4,2]
returns true

Swapping the 5 and the 2 gives [1, 2, 3, 4, 5].

Example 2

nums [3,1,2]
returns false

No single swap sorts it: [1, 3, 2], [2, 1, 3] and [3, 2, 1] are all unsorted.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Sorting and searching problems