Modify given array to a non-decreasing array by rotation
Last Updated :
02 Dec, 2023
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>
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
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).
Similar Reads
C++ Program to 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: YesExplanation:Â After
2 min read
C++ Program to Print all possible rotations of a given Array
Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: Input: arr[] = {1, 2, 3, 4} Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} Explanation: Initial arr[] = {1, 2, 3, 4} After first rotation arr[] = {4, 1, 2, 3} After second rotat
3 min read
C++ Program to Check if it is possible to make array increasing or decreasing by rotating the array
Given an array arr[] of N distinct elements, the task is to check if it is possible to make the array increasing or decreasing by rotating the array in any direction.Examples: Input: arr[] = {4, 5, 6, 2, 3} Output: Yes Array can be rotated as {2, 3, 4, 5, 6}Input: arr[] = {1, 2, 4, 3, 5} Output: No
4 min read
Circular rotation of an array using deque in C++
Given an array arr[] of integers and another integer D, the task is to perform D circular rotations on the array and print the modified array. Examples: Input: Arr[] = {1, 2, 3, 4, 5, 6}, D = 2 Output: 5 6 1 2 3 4 Input: Arr[] = {1, 2, 3}, D = 2 Output: 2 3 1 Approach: Using Deque in C++, a rotation
2 min read
C++ Program to Maximum sum of i*arr[i] among all rotations of a given array
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 +
6 min read
C++ Program to Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]. Examples :Â Â Input: arr[] = {1, 20, 2, 10} Output: 72 We can get 72 by rotating array twice. {2, 10, 1, 20} 20*3 + 1*2 + 10*1 + 2*0 = 72 I
4 min read
C++ Program to Maximize count of corresponding same elements in given Arrays by Rotation
Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples:  Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3,
3 min read
C++ Program to Find the Mth element of the Array after K left rotations
Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation:Â The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ]
3 min read
C++ Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following are steps. 1) Store last element in a variable say x. 2) Shift all eleme
3 min read
C++ Program to Count rotations required to sort given array in non-increasing order
Given an array arr[] consisting of N integers, the task is to sort the array in non-increasing order by minimum number of anti-clockwise rotations. If it is not possible to sort the array, then print "-1". Otherwise, print the count of rotations. Examples: Input: arr[] = {2, 1, 5, 4, 3}Output: 2Expl
3 min read