Open In App

Modify given array to a non-decreasing array by rotation

Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a
// non-decreasing array can be obtained
// by rotating the original array
void rotateArray(vector<int>& arr, int N)
{
    // Stores copy of original array
    vector<int> v = arr;
 
    // Sort the given vector
    sort(v.begin(), v.end());
 
    // Traverse the array
    for (int i = 1; i <= N; ++i) {
 
        // Rotate the array by 1
        rotate(arr.begin(),
               arr.begin() + 1, arr.end());
 
        // If array is sorted
        if (arr == v) {
 
            cout << "YES" << endl;
            return;
        }
    }
 
    // If it is not possible to
    // sort the array
    cout << "NO" << endl;
}
 
// Driver Code
int main()
{
    // Given array
    vector<int> arr = { 3, 4, 5, 1, 2 };
 
    // Size of the array
    int N = arr.size();
 
    // Function call to check if it is possible
    // to make array non-decreasing by rotating
    rotateArray(arr, N);
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
  // Function to check if a
  // non-decreasing array can be obtained
  // by rotating the original array
  static void rotateArray(int[] arr, int N)
  {
    // Stores copy of original array
    int[] v = arr;
 
    // Sort the given vector
    Arrays.sort(v);
 
    // Traverse the array
    for (int i = 1; i <= N; ++i) {
 
      // Rotate the array by 1
      int 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) {
 
        System.out.print("YES");
        return;
      }
    }
 
    // If it is not possible to
    // sort the array
    System.out.print("NO");
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    // Given array
    int[] arr = { 3, 4, 5, 1, 2 };
 
    // Size of the array
    int N = arr.length;
 
    // Function call to check if it is possible
    // to make array non-decreasing by rotating
    rotateArray(arr, N);
  }
}
 
// This code is contributed by splevel62.


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.


C#




// C# program to implement
// the above approach
using System;
class GFG
{
   
  // Function to check if a
  // non-decreasing array can be obtained
  // by rotating the original array
  static void rotateArray(int[] arr, int N)
  {
     
    // Stores copy of original array
    int[] v = arr;
 
    // Sort the given vector
    Array.Sort(v);
 
    // Traverse the array
    for (int i = 1; i <= N; ++i) {
 
      // Rotate the array by 1
      int 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) {
 
        Console.Write("YES");
        return;
      }
    }
 
    // If it is not possible to
    // sort the array
    Console.Write("NO");
  }
 
 
// Driver code
public static void Main()
{
    // Given array
    int[] arr = { 3, 4, 5, 1, 2 };
 
    // Size of the array
    int N = arr.Length;
 
    // Function call to check if it is possible
    // to make array non-decreasing by rotating
    rotateArray(arr, N);
}
}
 
// This code is contributed by susmitakundugoaldanga.


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to check if a
// non-decreasing array can be obtained
// by rotating the original array
function rotateArray(arr, N) {
 
    // Stores copy of original array
    let v = arr;
 
    // Sort the given vector
    v.sort((a, b) => a - b);
 
    // Traverse the array
    for (let i = 1; i <= N; ++i) {
 
        // Rotate the array by 1
        let x = arr[N - 1];
        i = N - 1;
        while (i--) {
            arr[i] = arr[i - 1];
            arr[0] = x;
        }
 
        // If array is sorted
 
        let isEqual = arr.every((e, i) => {
            return arr[i] == v[i]
        })
 
 
        if (isEqual) {
            document.write("YES");
            return;
        }
    }
 
    // If it is not possible to
    // sort the array
    document.write("NO");
}
 
 
// Driver code
 
// Given array
let arr = [3, 4, 5, 1, 2];
 
// Size of the array
let N = arr.length;
 
// Function call to check if it is possible
// to make array non-decreasing by rotating
rotateArray(arr, N);
 
// This code is contributed by _saurabh_jaiswal
 
</script>


Output

YES





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

Approach#2: Using Sorting and Indexing

The approach used in this code is to iterate through all possible rotations of the input array and check whether the array can be modified to a non-decreasing array by rotation. To check this, the code first sorts the input array to get the non-decreasing order. Then, it iterates through all possible rotations of the input array by right-rotating the array one element at a time. For each rotation, the code checks whether the rotated array is equal to the sorted array. If it is, then the input array can be modified to a non-decreasing array by rotation, and the code returns ‘Yes’. Otherwise, it continues rotating the array until all possible rotations have been checked. If none of the rotations result in a non-decreasing array, then the code returns ‘No’.

Algorithm

1. Sort the input array and store it in a variable sorted_arr.
2. For i = 0 to len(arr)-1, do the following:
a. If arr is equal to sorted_arr, return ‘Yes’.
b. Right-rotate the array by one element by slicing and concatenating, and store the result in arr.
3. If none of the rotations result in a non-decreasing array, return ‘No’.

C++




#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;  
 
// Function to check if the array is non-decreasing
string checkNonDecreasingArray(vector<int>& arr) {
    vector<int> sortedArr = arr;
    sort(sortedArr.begin(), sortedArr.end());  // Sort a copy of the array
 
    for (size_t i = 0; i < arr.size(); i++) {
        if (arr == sortedArr) {
            return "Yes";
        }
 
        // Right rotate the array
        int firstElement = arr[0];
        for (size_t j = 0; j < arr.size() - 1; j++) {
            arr[j] = arr[j + 1];
        }
        arr[arr.size() - 1] = firstElement;
    }
 
    return "No";
}
// Driver Code
int main() {
    vector<int> arr = {3, 4, 5, 1, 2};
    string result = checkNonDecreasingArray(arr);
    cout << result << endl;  // Output: Yes
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class NonDecreasingArrayCheck {
    // Function to check if the array is non-decreasing
    public static String checkNonDecreasingArray(List<Integer> arr) {
        List<Integer> sortedArr = new ArrayList<>(arr);
        Collections.sort(sortedArr);  // Sort a copy of the array
 
        for (int i = 0; i < arr.size(); i++) {
            if (arr.equals(sortedArr)) {
                return "Yes";
            }
 
            // Right rotate the array
            int firstElement = arr.get(0);
            for (int j = 0; j < arr.size() - 1; j++) {
                arr.set(j, arr.get(j + 1));
            }
            arr.set(arr.size() - 1, firstElement);
        }
 
        return "No";
    }
 
    // Driver Code
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(3);
        arr.add(4);
        arr.add(5);
        arr.add(1);
        arr.add(2);
 
        String result = checkNonDecreasingArray(arr);
        System.out.println(result);  // Output: Yes
    }
}


Python3




def check_non_decreasing_array(arr):
    sorted_arr = sorted(arr)
    for i in range(len(arr)):
        if arr == sorted_arr:
            return 'Yes'
        arr = arr[1:] + [arr[0]]  # right rotate the array
    return 'No'
     
# Example usage
arr = [3, 4, 5, 1, 2]
print(check_non_decreasing_array(arr)) # Output: Yes


C#




using System;
using System.Collections.Generic;
 
class MainClass
{
    // Function to check if the array is non-decreasing
    static string CheckNonDecreasingArray(List<int> arr)
    {
        List<int> sortedArr = new List<int>(arr);
        sortedArr.Sort();  // Sort a copy of the array
 
        for (int i = 0; i < arr.Count; i++)
        {
            if (IsEqual(arr, sortedArr))
            {
                return "Yes";
            }
 
            // Right rotate the array
            int firstElement = arr[0];
            arr.RemoveAt(0);
            arr.Add(firstElement);
        }
 
        return "No";
    }
 
    // Function to check if two lists are equal
    static bool IsEqual(List<int> list1, List<int> list2)
    {
        if (list1.Count != list2.Count)
        {
            return false;
        }
 
        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        List<int> arr = new List<int> { 3, 4, 5, 1, 2 };
        string result = CheckNonDecreasingArray(arr);
        Console.WriteLine(result);  // Output: Yes
    }
}


Javascript




// Function to check if the array is non-decreasing
function checkNonDecreasingArray(arr) {
    const sortedArr = [...arr].sort((a, b) => a - b); // Sort a copy of the array
 
    for (let i = 0; i < arr.length; i++) {
        if (JSON.stringify(arr) === JSON.stringify(sortedArr)) {
            return "Yes";
        }
 
        // Right rotate the array
        const firstElement = arr.shift();
        arr.push(firstElement);
    }
 
    return "No";
}
 
// Driver Code
const arr = [3, 4, 5, 1, 2];
const result = checkNonDecreasingArray(arr);
console.log(result); // Output: Yes


Output

Yes






Time Complexity:  O(n^2) because it uses a nested loop to iterate through all possible rotations of the input array. The outer loop iterates n times, and the inner loop iterates up to n times. The sorting operation also takes O(n log n) time. Therefore, the overall time complexity is O(n^2 + n log n) = O(n^2).

Space Complexity:  O(n) because it uses additional space to store the sorted array and the rotated arrays. The sorted array takes O(n) space, and each rotated array takes O(n) space. Therefore, the overall space complexity is O(n + n) = O(n).



Last Updated : 02 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads