Modify given array to a non-decreasing array by rotation
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++
#include <bits/stdc++.h>
using namespace std;
void rotateArray(vector< int >& arr, int N)
{
vector< int > v = arr;
sort(v.begin(), v.end());
for ( int i = 1; i <= N; ++i) {
rotate(arr.begin(),
arr.begin() + 1, arr.end());
if (arr == v) {
cout << "YES" << endl;
return ;
}
}
cout << "NO" << endl;
}
int main()
{
vector< int > arr = { 3, 4, 5, 1, 2 };
int N = arr.size();
rotateArray(arr, N);
}
|
Java
import java.util.*;
class GFG{
static void rotateArray( int [] arr, int N)
{
int [] v = arr;
Arrays.sort(v);
for ( int i = 1 ; i <= N; ++i) {
int x = arr[N - 1 ];
i = N - 1 ;
while (i > 0 ){
arr[i] = arr[i - 1 ];
arr[ 0 ] = x;
i -= 1 ;
}
if (arr == v) {
System.out.print( "YES" );
return ;
}
}
System.out.print( "NO" );
}
public static void main(String[] args)
{
int [] arr = { 3 , 4 , 5 , 1 , 2 };
int N = arr.length;
rotateArray(arr, N);
}
}
|
Python3
def rotateArray(arr, N):
v = arr
v.sort(reverse = False )
for i in range ( 1 , N + 1 , 1 ):
x = arr[N - 1 ]
i = N - 1
while (i > 0 ):
arr[i] = arr[i - 1 ]
arr[ 0 ] = x
i - = 1
if (arr = = v):
print ( "YES" )
return
print ( "NO" )
if __name__ = = '__main__' :
arr = [ 3 , 4 , 5 , 1 , 2 ]
N = len (arr)
rotateArray(arr, N)
|
C#
using System;
class GFG
{
static void rotateArray( int [] arr, int N)
{
int [] v = arr;
Array.Sort(v);
for ( int i = 1; i <= N; ++i) {
int x = arr[N - 1];
i = N - 1;
while (i > 0){
arr[i] = arr[i - 1];
arr[0] = x;
i -= 1;
}
if (arr == v) {
Console.Write( "YES" );
return ;
}
}
Console.Write( "NO" );
}
public static void Main()
{
int [] arr = { 3, 4, 5, 1, 2 };
int N = arr.Length;
rotateArray(arr, N);
}
}
|
Javascript
<script>
function rotateArray(arr, N) {
let v = arr;
v.sort((a, b) => a - b);
for (let i = 1; i <= N; ++i) {
let x = arr[N - 1];
i = N - 1;
while (i--) {
arr[i] = arr[i - 1];
arr[0] = x;
}
let isEqual = arr.every((e, i) => {
return arr[i] == v[i]
})
if (isEqual) {
document.write( "YES" );
return ;
}
}
document.write( "NO" );
}
let arr = [3, 4, 5, 1, 2];
let N = arr.length;
rotateArray(arr, N);
</script>
|
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;
string checkNonDecreasingArray(vector< int >& arr) {
vector< int > sortedArr = arr;
sort(sortedArr.begin(), sortedArr.end());
for ( size_t i = 0; i < arr.size(); i++) {
if (arr == sortedArr) {
return "Yes" ;
}
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" ;
}
int main() {
vector< int > arr = {3, 4, 5, 1, 2};
string result = checkNonDecreasingArray(arr);
cout << result << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NonDecreasingArrayCheck {
public static String checkNonDecreasingArray(List<Integer> arr) {
List<Integer> sortedArr = new ArrayList<>(arr);
Collections.sort(sortedArr);
for ( int i = 0 ; i < arr.size(); i++) {
if (arr.equals(sortedArr)) {
return "Yes" ;
}
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" ;
}
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);
}
}
|
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 ]]
return 'No'
arr = [ 3 , 4 , 5 , 1 , 2 ]
print (check_non_decreasing_array(arr))
|
C#
using System;
using System.Collections.Generic;
class MainClass
{
static string CheckNonDecreasingArray(List< int > arr)
{
List< int > sortedArr = new List< int >(arr);
sortedArr.Sort();
for ( int i = 0; i < arr.Count; i++)
{
if (IsEqual(arr, sortedArr))
{
return "Yes" ;
}
int firstElement = arr[0];
arr.RemoveAt(0);
arr.Add(firstElement);
}
return "No" ;
}
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 ;
}
public static void Main( string [] args)
{
List< int > arr = new List< int > { 3, 4, 5, 1, 2 };
string result = CheckNonDecreasingArray(arr);
Console.WriteLine(result);
}
}
|
Javascript
function checkNonDecreasingArray(arr) {
const sortedArr = [...arr].sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (JSON.stringify(arr) === JSON.stringify(sortedArr)) {
return "Yes" ;
}
const firstElement = arr.shift();
arr.push(firstElement);
}
return "No" ;
}
const arr = [3, 4, 5, 1, 2];
const result = checkNonDecreasingArray(arr);
console.log(result);
|
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
Share your thoughts in the comments
Please Login to comment...