Check if an array is sorted and rotated in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of n unique values. We have to check whether this array is sorted and rotated anti-clockwise. Here at least one rotation is required so a fully sorted array is not considered as sorted and rotated.

So, if the input is like nums = [4,5,6,8,1,3], then the output will be True as we can rotate two times to the clockwise direction then it will be sorted like [1, 3, 4, 5, 6, 8].

To solve this, we will follow these steps −

  • min_element := minimum of nums
  • min_index := index of min_element in nums
  • before_sorted := True
  • for i in range 1 to min_index - 1, do
    • if nums[i] < nums[i - 1], then
      • before_sorted := False
      • come out from loop
  • after_sorted := True
  • for i in range min_index + 1 to size of nums - 1, do
    • if nums[i] < nums[i - 1], then
      • after_sorted := False
      • come out from loop
  • if before_sorted and after_sorted are true and last element of nums < nums[0], then
    • return True
  • otherwise,
    • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums):
   min_element = 999999
   min_index = -1
   min_element = min(nums)
   min_index = nums.index(min_element) before_sorted = True
   for i in range(1, min_index):
      if nums[i] < nums[i - 1]:
         before_sorted = False
         break
   after_sorted = True
   for i in range(min_index + 1, len(nums)):
      if nums[i] < nums[i - 1]:
         after_sorted = False
         break
   if before_sorted and after_sorted and nums[-1] < nums[0]:
      return True
   else:
      return False
nums = [4,5,6,8,1,3]
print(solve(nums))

Input

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

Output

True
raja
Published on 30-Dec-2020 17:13:23
Advertisements