Program to check right rotation forms increasing or decreasing array with first n natural numbers or not in Python


Suppose we have a list of numbers called nums, where n elements are present. We have to chesk whether we can make a list with first n natural numbers either in increasing or decreasing fashion, like [1, 2, ..., n] or [n, n - 1, ..., 1] by shifting nums to the right any number of times or not.

So, if the input is like nums = [5,6,1,2,3,4], then the output will be True, because we can shift them four times to make the array [1,2,3,4,5,6]

To solve this, we will follow these steps −

  • n := size of nums
  • for i in range 1 to n - 1, do
    • if |nums[i - 1] - nums[i]| is not 1 and |nums[i - 1] - nums[i]| is not n-1, then
      • return False
  • return True

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   n = len(nums)
   for i in range(1, n):
      if abs(nums[i - 1] - nums[i]) != 1 and abs(nums[i - 1] - nums[i]) != n - 1:
         return False
   return True

nums = [5,6,1,2,3,4]
print(solve(nums))

Input

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

Output

True

Updated on: 14-Oct-2021

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements