Given an array of integers, the task is to check if the array is sorted (increasing order) and rotated after some number of position or not.
For Example
Input-1:
N = [7, 8, 9, 4, 5, 6]
Output:
True
Explanation: Since the given array is in increasing order and the elements after the 3rd position are rotated, we will return True in this case.
Input-2:
N = [1, 5, 7, 6, 2, 3]
Output:
False
Explanation: Since the given array is neither in increasing order nor rotated with some specific position, the output is False.
We have an array with the element either in increasing order or unsorted. If the array has to be sorted and rotated, then at least one element will be there such that N[i] > N[i+1].
Thus, for every N[i], we will count if there lies any element which satisfies the condition and return True or False accordingly.
#include <bits/stdc++.h> using namespace std; bool checkSortedandRotated(int * arr, int n) { int count = 0; for (int i = 0; i < n; i++) { if (arr[i] > arr[(i + 1) % n]) count++; } return (count <= 1); } int main() { int arr[] = {5,6,7,1,2,3,4}; int n = sizeof(arr) / sizeof(int); if (checkSortedandRotated(arr, n)) { cout << "True" << endl; } else { cout << "False" << endl; } return 0; }
Running the above code will generate the output as,
True
Since the given array [5, 6, 7, 1, 2, 3, 4] is sorted and rotated from the 3rd position, we get the output as 'True' in this case.