Check if an array is sorted and rotated in C++

C++Server Side ProgrammingProgramming

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.

Approach to Solve this Problem

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.

  • Take Input of an array element.
  • A Boolean function checkSortedandRotated(int *arr, int n) takes an array and its size as the input and returns true if the array is sorted and rotated otherwise false.
  • Iterate over the whole array and count the number of elements which are (arr[i] > arr[i+1]%n). If the count is '1', then return True, otherwise return False.
  • Return the output.

Example

Live Demo

#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,

Output

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.

raja
Published on 23-Feb-2021 09:19:05
Advertisements