Problem 363158 · easy · Level 03 Linear Management & Searching

One Swap Away

sorting · comparison with sorted copy

Given a list of integers nums, return True if it is already sorted in non-decreasing order or can be made non-decreasing by swapping the values at exactly one pair of positions. Otherwise return False.

Examples

Input:  nums = [1, 5, 3, 4, 2]
Output: True
Explanation: Swapping the 5 and the 2 gives [1, 2, 3, 4, 5].
Input:  nums = [3, 1, 2]
Output: False
Explanation: No single swap sorts it.

Constraints

  • 0 <= len(nums) <= 10**5
  • Duplicates are allowed, e.g. [2, 1, 1] is one swap away from sorted.
  • Target complexity: O(n log n).

Goals

  • Compare a list against its sorted version position by position
  • Reason about how many positions a single swap can fix
  • Handle duplicates correctly
Starting Python…