C++ Program to Modify given array to a non-decreasing array by rotation
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:
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);
}
|
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!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...