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

PythonServer Side ProgrammingProgramming

Suppose we have an array of numbers called nums, where all elements are unique. We have to check whether nums is almost sorted or not. As we know 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.

So, if the input is like nums = [10, 30, 20, 40], then the output will be True as 10 is placed at its original place and all other elements are at max one place away from their actual position.

To solve this, we will follow these steps −

  • i := 0
  • while i < size of nums - 1, do
    • if nums[i] > nums[i + 1], then
      • swap nums[i] and nums[i + 1]
      • i := i + 1
    • i := i + 1
  • for i in range 0 to size of nums - 1, do
    • if nums[i] > nums[i + 1], then
      • return False
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums):
   i = 0
   while i < len(nums) - 1:
      if nums[i] > nums[i + 1]:
         nums[i], nums[i + 1] = nums[i + 1], nums[i]
         i += 1
      i += 1
   for i in range(len(nums) - 1):
      if nums[i] > nums[i + 1]:
         return False
   return True
nums = [10, 30, 20, 40]
print(solve(nums))

Input

[10, 30, 20, 40]

Output

True
raja
Published on 18-Jan-2021 17:12:56
Advertisements