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

PythonServer Side ProgrammingProgramming

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 element 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].

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 −

 Live Demo

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(solve(nums))

Input

[1, 0, 3, 2, 5, 4]

Output

True
raja
Published on 19-Jan-2021 04:26:33
Advertisements