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

Algorithm

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))

The output of the above code is:

True

How It Works

The algorithm checks if adjacent elements in the array have a difference of either 1 or (n-1). This ensures that the array can be rotated to form either an increasing sequence [1,2,...,n] or decreasing sequence [n,n-1,...,1].

For the example [5,6,1,2,3,4]:

  • |5-6| = 1 ?
  • |6-1| = 5 = (6-1) ?
  • |1-2| = 1 ?
  • |2-3| = 1 ?
  • |3-4| = 1 ?

Testing with Different Cases

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

# Test cases
test_cases = [
    [5, 6, 1, 2, 3, 4],  # Can form [1,2,3,4,5,6]
    [3, 2, 1, 6, 5, 4],  # Can form [6,5,4,3,2,1] 
    [1, 3, 2, 4, 5, 6],  # Cannot form valid sequence
]

for i, nums in enumerate(test_cases):
    result = solve(nums)
    print(f"Test {i+1}: {nums} ? {result}")

The output of the above code is:

Test 1: [5, 6, 1, 2, 3, 4] ? True
Test 2: [3, 2, 1, 6, 5, 4] ? True
Test 3: [1, 3, 2, 4, 5, 6] ? False

Conclusion

This algorithm efficiently checks if an array can be right-rotated to form a sequence of first n natural numbers in either increasing or decreasing order. It works by verifying that adjacent elements differ by either 1 or (n-1), ensuring rotational validity.

Updated on: 2026-03-26T16:36:27+05:30

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements