Check if it is possible to sort an array with conditional swapping of adjacent allowed in Python

Suppose we have an unordered array of numbers called nums and all elements are in range 0 to n-1. We can swap adjacent elements in nums as many times as required but only when the absolute difference between these elements is 1. We have to check whether we can sort the nums or not.

So, if the input is like nums = [1, 0, 3, 2, 5, 4], then the output will be True as we can swap these pairs [(1, 0), (3, 2), (5, 4)] to sort [0, 1, 2, 3, 4, 5].

Algorithm

To solve this, we will follow these steps ?

  • for i in range 0 to size of nums - 2, do
    • if nums[i] > nums[i+1], then
      • if nums[i] - nums[i+1] is same as 1, then
        • exchange nums[i] and nums[i+1]
      • otherwise,
        • return False
  • return True

Example

Let us see the following implementation to get better understanding ?

def solve(nums):
    for i in range(len(nums) - 1):
        if nums[i] > nums[i+1]:
            if nums[i] - nums[i+1] == 1:
                nums[i], nums[i+1] = nums[i+1], nums[i]
            else:
                return False
    return True

nums = [1, 0, 3, 2, 5, 4]
print("Input:", nums)
result = solve(nums)
print("Can be sorted:", result)
print("After processing:", nums)

The output of the above code is ?

Input: [1, 0, 3, 2, 5, 4]
Can be sorted: True
After processing: [0, 1, 2, 3, 4, 5]

How It Works

The algorithm performs a single pass through the array. When it finds two adjacent elements where the first is greater than the second, it checks if their difference is exactly 1. If yes, it swaps them; otherwise, it returns False since sorting is impossible with the given constraint.

Testing with Different Cases

def solve(nums):
    for i in range(len(nums) - 1):
        if nums[i] > nums[i+1]:
            if nums[i] - nums[i+1] == 1:
                nums[i], nums[i+1] = nums[i+1], nums[i]
            else:
                return False
    return True

# Test case 1: Sortable array
test1 = [1, 0, 3, 2, 5, 4]
print("Test 1:", test1, "?", solve(test1.copy()))

# Test case 2: Already sorted
test2 = [0, 1, 2, 3, 4, 5]
print("Test 2:", test2, "?", solve(test2.copy()))

# Test case 3: Cannot be sorted (difference > 1)
test3 = [3, 0, 1, 2]
print("Test 3:", test3, "?", solve(test3.copy()))

The output of the above code is ?

Test 1: [1, 0, 3, 2, 5, 4] ? True
Test 2: [0, 1, 2, 3, 4, 5] ? True
Test 3: [3, 0, 1, 2] ? False

Conclusion

This solution uses a greedy approach with O(n) time complexity. The key insight is that we can only swap adjacent elements with absolute difference 1, so we fix inversions as we encounter them during a single pass.

Updated on: 2026-03-25T15:13:28+05:30

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements