Check if given array is almost sorted (elements are at-most one position away) in Python

Suppose we have an array of numbers where all elements are unique. We need to check whether the array is almost sorted or not. An array is almost sorted when any of its elements can occur at a maximum of 1 distance away from its original position in the sorted array.

For example, if we have nums = [10, 30, 20, 40], the output will be True because 10 is at its correct position and all other elements are at most one place away from their actual sorted position.

Algorithm

To solve this problem, we follow these steps:

  • Initialize i = 0
  • While i < len(nums) - 1:
    • If nums[i] > nums[i + 1], swap them and increment i
    • Otherwise, just increment i
  • After one pass, check if the array is sorted
  • If any adjacent pair is still out of order, return False
  • Otherwise, return True

Implementation

def is_almost_sorted(nums):
    # Make a copy to avoid modifying original array
    arr = nums.copy()
    
    i = 0
    while i < len(arr) - 1:
        if arr[i] > arr[i + 1]:
            # Swap adjacent elements
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
            i += 1
        i += 1
    
    # Check if array is now sorted
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False
    
    return True

# Test with example
nums = [10, 30, 20, 40]
print(f"Array: {nums}")
print(f"Is almost sorted: {is_almost_sorted(nums)}")
Array: [10, 30, 20, 40]
Is almost sorted: True

Additional Examples

Let's test with more examples to understand the concept better:

def is_almost_sorted(nums):
    arr = nums.copy()
    
    i = 0
    while i < len(arr) - 1:
        if arr[i] > arr[i + 1]:
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
            i += 1
        i += 1
    
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False
    
    return True

# Test cases
test_cases = [
    [10, 30, 20, 40],     # Almost sorted
    [1, 2, 3, 4],         # Already sorted
    [2, 1, 4, 3],         # Almost sorted
    [3, 1, 2, 4],         # Not almost sorted
    [1, 3, 2, 5, 4]       # Almost sorted
]

for i, nums in enumerate(test_cases, 1):
    result = is_almost_sorted(nums)
    print(f"Test {i}: {nums} -> {result}")
Test 1: [10, 30, 20, 40] -> True
Test 2: [1, 2, 3, 4] -> True
Test 3: [2, 1, 4, 3] -> True
Test 4: [3, 1, 2, 4] -> False
Test 5: [1, 3, 2, 5, 4] -> True

How It Works

The algorithm performs a single pass through the array, swapping adjacent out-of-order elements. If the array is almost sorted, this single pass will be sufficient to sort it completely. After the pass, we verify if the array is sorted − if yes, the original array was almost sorted.

Time Complexity

The time complexity is O(n) where n is the length of the array, as we make at most two passes through the array. The space complexity is O(n) for creating a copy of the input array.

Conclusion

This algorithm efficiently determines if an array is almost sorted by performing adjacent swaps in a single pass. If the array becomes sorted after one pass, it was almost sorted initially.

Updated on: 2026-03-25T15:05:32+05:30

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements