Skip to content
Related Articles

Related Articles

Python3 Program to Modify given array to a non-decreasing array by rotation

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 27 Jan, 2022

Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it’s not possible to do so, then print “No“. Otherwise, print “Yes“.

Examples:

Input: arr[] = {3, 4, 5, 1, 2}
Output: Yes
Explanation: After 2 right rotations, the array arr[] modifies to {1, 2, 3, 4, 5}

Input: arr[] = {1, 2, 4, 3}
Output: No

Approach: The idea is based on the fact that a maximum of N distinct arrays can be obtained by rotating the given array and check for each individual rotated array, whether it is non-decreasing or not. Follow the steps below to solve the problem:

  • Initialize a vector, say v, and copy all the elements of the original array into it.
  • Sort the vector v.
  • Traverse the original array and perform the following steps:
    • Rotate by 1 in each iteration.
    • If the array becomes equal to vector v, print “Yes“. Otherwise, print “No“.

Below is the implementation of the above approach:

Python3




# Python 3 program for the above approach
  
  
# Function to check if a
# non-decreasing array can be obtained
# by rotating the original array
def rotateArray(arr, N):
    
    # Stores copy of original array
    v = arr
  
    # Sort the given vector
    v.sort(reverse = False)
  
    # Traverse the array
    for i in range(1, N + 1, 1):
        
        # Rotate the array by 1
        x = arr[N - 1]
        i = N - 1
        while(i > 0):
            arr[i] = arr[i - 1]
            arr[0] = x
            i -= 1
              
        # If array is sorted
        if (arr == v):
            print("YES")
            return
  
    # If it is not possible to
    # sort the array
    print("NO")
  
# Driver Code
if __name__ == '__main__':
    
    # Given array
    arr =  [3, 4, 5, 1, 2]
  
    # Size of the array
    N = len(arr)
  
    # Function call to check if it is possible
    # to make array non-decreasing by rotating
    rotateArray(arr, N)
      
    # This code is contributed by ipg2016107.

Output

YES

Time Complexity: O(N2)
Auxiliary Space: O(N)

Please refer complete article on Modify given array to a non-decreasing array by rotation for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!