Sortable With One Swap
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
0 <= len(nums) <= 100-1000 <= nums[i] <= 1000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Sorting and searching problems
- Sorting the SentenceEasy
- Find in a Mountain ListMedium
- Find in a Rotated ListMedium
- H-IndexMedium
- K Closest ValuesMedium
- Kth Smallest Pair SumMedium
- Least Truck CapacityMedium
- Merge IntervalsMedium