Check if it is possible to sort the array after rotating it in Python


Suppose we have a list of numbers called nums, we have to check whether we can sort nums or not by using rotation. By rotation we can shift some contiguous elements from the end of nums and place it in the front of the array.

So, if the input is like nums = [4,5,6,1,2,3], then the output will be True as we can sort by rotating last three elements and send them back to first.

To solve this, we will follow these steps −

  • n := size of nums
  • if nums is sorted, then
    • return True
  • otherwise,
    • status := True
    • for i in range 0 to n - 2, do
      • if nums[i] > nums[i + 1], then
        • come out from loop
    • i := i + 1
    • for k in range i to n - 2, do
      • if nums[k] > nums[k + 1], then
        • status := False
        • come out from loop
    • if status is false, then
      • return False
    • otherwise,
      • if nums[n - 1] <= nums[0], then
        • return True
      • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums):
   n = len(nums)
   if all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)):
      return True
   else :
      status = True
      for i in range(n - 1) :
         if nums[i] > nums[i + 1] :
            break
      i += 1
      for k in range(i, n - 1) :
         if nums[k] > nums[k + 1]:
            status = False
            break
      if not status:
         return False
      else :
         if nums[n - 1] <= nums[0]:
            return True
         return False
nums = [4,5,6,1,2,3]
print(solve(nums))

Input

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

Output

True

Updated on: 19-Jan-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements