Check if array can be sorted with one swap in Python

Sorting is a task used to organize numbers in increasing order. Usually, we use sorting algorithms to do this, but in most cases, the array is almost sorted, with only two or three numbers in the wrong position.

In such scenarios, instead of sorting the entire array, we can check if swapping just one pair of elements will make the entire array sorted.

Problem Definition

Given an array with distinct integers, we need to find if it can become completely sorted by swapping only one pair of elements. We are not performing the swap, just checking if such a swap is possible.

Scenario 1

<b>Input:</b> [1, 3, 2, 4, 5]
<b>Output:</b> True
<b>Explanation:</b> If we swap 3 and 2, we get [1, 2, 3, 4, 5], which is sorted.

Scenario 2

<b>Input:</b> [1, 5, 3, 2, 4]
<b>Output:</b> False
<b>Explanation:</b> More than two elements are out of place compared to the sorted array [1, 2, 3, 4, 5].

Algorithm

The following algorithm checks if an array can be sorted with one swap ?

  • Step 1: Create a sorted version of the original array
  • Step 2: Compare both arrays and collect indices where elements differ
  • Step 3: If no mismatches exist, return True (array is already sorted)
  • Step 4: If exactly two indices mismatch, try swapping those elements
  • Step 5: Return True if the array becomes sorted after one swap, else False

Implementation

Here's the implementation to check if an array can be sorted with one swap ?

def can_sort_with_one_swap(arr):
    # Create sorted version
    sorted_arr = sorted(arr)
    
    # Find mismatched indices
    mismatches = []
    for i in range(len(arr)):
        if arr[i] != sorted_arr[i]:
            mismatches.append(i)
    
    # Already sorted
    if len(mismatches) == 0:
        return True
    
    # Exactly two mismatches - try swapping
    elif len(mismatches) == 2:
        i, j = mismatches
        # Create copy to avoid modifying original
        temp_arr = arr.copy()
        temp_arr[i], temp_arr[j] = temp_arr[j], temp_arr[i]
        return temp_arr == sorted_arr
    
    # More than 2 mismatches - impossible with one swap
    else:
        return False

# Test with different arrays
test_arrays = [
    [1, 3, 2, 4, 5],     # Can be sorted with one swap
    [1, 5, 3, 2, 4],     # Cannot be sorted with one swap
    [1, 2, 3, 4, 5],     # Already sorted
    [2, 1]               # Can be sorted with one swap
]

for arr in test_arrays:
    result = can_sort_with_one_swap(arr)
    print(f"Array {arr}: {result}")

The output of the above code is ?

Array [1, 3, 2, 4, 5]: True
Array [1, 5, 3, 2, 4]: False
Array [1, 2, 3, 4, 5]: True
Array [2, 1]: True

How It Works

The algorithm works by comparing the original array with its sorted version ?

  • 0 mismatches: Array is already sorted
  • 2 mismatches: Check if swapping those two elements makes it sorted
  • >2 mismatches: Impossible to sort with just one swap

Time and Space Complexity

Aspect Complexity Reason
Time O(n log n) Sorting the array
Space O(n) Storing sorted array and copy

Conclusion

This approach efficiently determines if an array can be sorted with one swap by comparing it with its sorted version. It's particularly useful for nearly-sorted arrays where only a few elements are out of place.

Updated on: 2026-03-25T14:21:31+05:30

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements