Open In App

Check if an array is sorted and rotated

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated clockwise. 

Note: A sorted array is not considered as sorted and rotated, i.e., there should be at least one rotation

Examples:

Input: arr[] = { 3, 4, 5, 1, 2 }
Output: YES
Explanation: The above array is sorted and rotated
Sorted array: {1, 2, 3, 4, 5}
Rotating this sorted array clockwise 
by 3 positions, we get: { 3, 4, 5, 1, 2}

Input: arr[] = {3, 4, 6, 1, 2, 5}
Output: NO

Check if an array is sorted and rotated by finding the pivot element(minimum element):

Find the minimum element in the array and if the array has been sorted and rotated then the elements before and after the minimum element will be in sorted order only.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int countAdjacentInversions(int arr[], int n) {
    int inversions = 0;
 
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            inversions++;
        }
    }
 
    return inversions;
}
 
bool checkRotatedAndSorted(int arr[], int n) {
    int inversions = countAdjacentInversions(arr, n);
 
    // If there are no inversions, the array is sorted.
    if (inversions == 0) {
        return true;
    }
 
    // If there is exactly one inversion and the last element is smaller
    // than the first element, the array is both sorted and rotated.
    if (inversions == 1 && arr[n - 1] < arr[0]) {
        return true;
    }
 
    // Otherwise, the array is not sorted and rotated.
    return false;
}
 
int main() {
    int arr[] = {4, 5, 1, 2, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    if (checkRotatedAndSorted(arr, n))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
 
    return 0;
}


Java




import java.io.*;
 
class GFG {
 
    // Function to count adjacent inversions
    static int countAdjacentInversions(int arr[], int n) {
        int inversions = 0;
 
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                inversions++;
            }
        }
 
        return inversions;
    }
 
    // Function to check if an array is sorted and rotated by counting adjacent inversions
    static boolean checkIfSortRotated(int arr[], int n) {
        int inversions = countAdjacentInversions(arr, n);
 
        // If there is only one inversion and the last element is smaller than the first element
        if (inversions == 1 && arr[n - 1] < arr[0]) {
            return true;
        }
 
        return false;
    }
 
    // Driver code
    public static void main(String[] args) {
        int arr[] = {5, 1, 2, 3, 4};
 
        int n = arr.length;
 
        // Function Call
        boolean x = checkIfSortRotated(arr, n);
        if (x == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


C#




// C# program to check if an
// array is sorted and rotated
// clockwise
 
using System;
 
class Program {
    static bool IsIncRotated(int[] arr, int n, int minIndex,
                             int maxIndex)
    {
        if (arr[0] < arr[n - 1])
            return false;
 
        return IsIncreasing(arr, 0, maxIndex)
            && IsIncreasing(arr, minIndex, n - 1);
    }
 
    static bool IsDecRotated(int[] arr, int n, int minIndex,
                             int maxIndex)
    {
        if (arr[0] > arr[n - 1])
            return false;
 
        return IsDecreasing(arr, 0, minIndex)
            && IsDecreasing(arr, maxIndex, n - 1);
    }
 
    static bool IsIncreasing(int[] arr, int l, int r)
    {
        for (int i = l + 1; i <= r; i++) {
            if (arr[i - 1] > arr[i])
                return false;
        }
        return true;
    }
 
    static bool IsDecreasing(int[] arr, int l, int r)
    {
        for (int i = l + 1; i <= r; i++) {
            if (arr[i - 1] < arr[i])
                return false;
        }
        return true;
    }
 
    static void CheckIfSortRotated(int[] arr)
    {
         
        int minIndex = 0;
        int maxIndex = 0;
 
        // Find the index of the minimum and maximum element
        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] < arr[minIndex])
                minIndex = i;
            if (arr[i] > arr[maxIndex])
                maxIndex = i;
        }
 
        bool res = false;
 
        if (maxIndex == minIndex - 1) {
            res = IsIncRotated(arr, arr.Length, minIndex,
                               maxIndex);
        }
 
        if (minIndex == maxIndex - 1) {
            res = IsDecRotated(arr, arr.Length, minIndex,
                               maxIndex);
        }
 
        if (res)
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
 
    static void Main()
    {
        int[] arr = { 10,20,14 };
        CheckIfSortRotated(arr);
    }
}
 
// This code is contributed
// by susmitabhattacharya2023.


Javascript




    // Javascript program to check if an
    // array is sorted and rotated
    // clockwise
 
function isIncRotated(arr, n, minIndex, maxIndex) {
    if (arr[0] < arr[n - 1]) {
        return false;
    }
 
    return isIncreasing(arr, 0, maxIndex) && isIncreasing(arr, minIndex, n - 1);
}
 
function isDecRotated(arr, n, minIndex, maxIndex) {
    if (arr[0] > arr[n - 1]) {
        return false;
    }
 
    return isDecreasing(arr, 0, minIndex) && isDecreasing(arr, maxIndex, n - 1);
}
 
function isIncreasing(arr, l, r) {
    for (let i = l + 1; i <= r; i++) {
        if (arr[i - 1] > arr[i]) {
            return false;
        }
    }
    return true;
}
 
function isDecreasing(arr, l, r) {
    for (let i = l + 1; i <= r; i++) {
        if (arr[i - 1] < arr[i]) {
            return false;
        }
    }
    return true;
}
 
function checkIfSortRotated(arr) {
    let minEle = Infinity;
    let maxEle = -Infinity;
    let minIndex = 0;
    let maxIndex = 0;
 
    // Find the index of the minimum and maximum element
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < arr[minIndex]) {
            minIndex = i;
        }
        if (arr[i] > arr[maxIndex]) {
            maxIndex = i;
        }
    }
 
    let res = false;
 
    if (maxIndex === minIndex - 1) {
        res = isIncRotated(arr, arr.length, minIndex, maxIndex);
    }
 
    if (minIndex === maxIndex - 1) {
        res = isDecRotated(arr, arr.length, minIndex, maxIndex);
    }
 
    if (res) {
        console.log("YES");
    } else {
        console.log("NO");
    }
}
 
let arr = [3, 4, 5, 1, 2];
checkIfSortRotated(arr);
 
 
// This code is contributed by susmitabhattacharya2023.


Python3




# Python3 program to check if an
# array is sorted and rotated clockwise
 
 
def isIncRotated(arr, n, minIndex, maxIndex):
    if arr[0] < arr[n - 1]:
        return False
 
    return isIncreasing(arr, 0, maxIndex) and isIncreasing(arr, minIndex, n - 1)
 
 
def isDecRotated(arr, n, minIndex, maxIndex):
    if arr[0] > arr[n - 1]:
        return False
 
    return isDecreasing(arr, 0, minIndex) and isDecreasing(arr, maxIndex, n - 1)
 
 
def isIncreasing(arr, l, r):
    for i in range(l + 1, r + 1):
        if arr[i - 1] > arr[i]:
            return False
    return True
 
 
def isDecreasing(arr, l, r):
    for i in range(l + 1, r + 1):
        if arr[i - 1] < arr[i]:
            return False
    return True
 
 
def checkIfSortRotated(arr):
    minEle = float('inf')
    maxEle = float('-inf')
    minIndex = 0
    maxIndex = 0
 
    # Find the index of the minimum & maximum element
    for i in range(len(arr)):
        if arr[i] < arr[minIndex]:
            minIndex = i
        if arr[i] > arr[maxIndex]:
            maxIndex = i
 
    res = False
 
    if maxIndex == minIndex - 1:
        res = isIncRotated(arr, len(arr), minIndex, maxIndex)
 
    if minIndex == maxIndex - 1:
        res = isDecRotated(arr, len(arr), minIndex, maxIndex)
 
    if res:
        print("YES")
    else:
        print("NO")
 
 
# Driver code
arr = [3, 4, 5, 1, 2]
checkIfSortRotated(arr)
 
# This code is contributed
# by susmitabhattacharya2023


Output

YES

Time Complexity: O(N)
Auxiliary Space: O (1)

Check if an array is sorted and rotated by counting adjacent inversions:

As the array is sorted and rotated, so the case when the previous element is greater than the current element will occur only once. If this occurs zero times or more than one times then the array is not properly sorted and rotated

Follow the given steps to solve the problem:

  • Take two variables to say x and y, initialized as 0
  • Now traverse the array
  • If the previous element is smaller than the current, increment x by one
  • Else increment y by one.
  • After traversal, if y is not equal to 1, return false.
  • Then compare the last element with the first element (0th element as current, and last element as previous.) i.e. if the last element is greater increase y by one else increase x by one
  • Again check if y equals one return true. i.e. Array is sorted and rotated. Else return false

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
bool checkRotatedAndSorted(int arr[], int n)
{
 
    // Your code here
    // Initializing two variables x,y as zero.
    int x = 0, y = 0;
 
    // Traversing array 0 to last element.
    // n-1 is taken as we used i+1.
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] < arr[i + 1])
            x++;
        else
            y++;
    }
 
    // If till now both x,y are greater than 1 means
    // array is not sorted. If both any of x,y is zero
    // means array is not rotated.
    if (y == 1) {
        // Checking for last element with first.
        if (arr[n - 1] < arr[0])
            x++;
        else
            y++;
 
        // Checking for final result.
        if (y == 1)
            return true;
    }
 
    // If still not true then definitely false.
    return false;
}
 
//  Driver Code Starts.
 
int main()
{
    int arr[] = { 4, 5, 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    if (checkRotatedAndSorted(arr, n))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
 
    return 0;
}


Java




import java.io.*;
 
class GFG {
 
    // Function to check if an array is
    // Sorted and rotated clockwise
    static boolean checkIfSortRotated(int arr[], int n)
    {
        // Initializing two variables x,y as zero.
        int x = 0, y = 0;
 
        // Traversing array 0 to last element.
        // n-1 is taken as we used i+1.
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] < arr[i + 1])
                x++;
            else
                y++;
        }
 
        // If till now both x,y are greater
        // than 1 means array is not sorted.
        // If both any of x,y is zero means
        // array is not rotated.
        if (y == 1) {
            // Checking for last element with first.
            if (arr[n - 1] < arr[0])
                x++;
            else
                y++;
 
            // Checking for final result.
            if (y == 1)
                return true;
        }
        // If still not true then definitely false.
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 5, 1, 2, 3, 4 };
 
        int n = arr.length;
 
        // Function Call
        boolean x = checkIfSortRotated(arr, n);
        if (x == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


C#




using System;
public class GFG {
 
    // Function to check if an array is
    // Sorted and rotated clockwise
    static bool checkIfSortRotated(int[] arr, int n)
    {
        // Initializing two variables x,y as zero.
        int x = 0, y = 0;
 
        // Traversing array 0 to last element.
        // n-1 is taken as we used i+1.
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] < arr[i + 1])
                x++;
            else
                y++;
        }
 
        // If till now both x,y are greater
        // than 1 means array is not sorted.
        // If both any of x,y is zero means
        // array is not rotated.
        if (y == 1) {
            // Checking for last element with first.
            if (arr[n - 1] < arr[0])
                x++;
            else
                y++;
 
            // Checking for readonly result.
            if (y == 1)
                return true;
        }
        // If still not true then definitely false.
        return false;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 5, 1, 2, 3, 4 };
 
        int n = arr.Length;
 
        // Function Call
        bool x = checkIfSortRotated(arr, n);
        if (x == true)
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}
 
// This code is contributed by umadevi9616


Javascript




// JavaScript Function to check if an array is
// Sorted and rotated clockwise
function checkIfSortRotated(arr, n)
    {
     
        // Initializing two variables x,y as zero.
        var x = 0, y = 0;
 
        // Traversing array 0 to last element.
        // n-1 is taken as we used i+1.
        for (var i = 0; i < n - 1; i++) {
            if (arr[i] < arr[i + 1])
                x++;
            else
                y++;
        }
 
        // If till now both x,y are greater
        // than 1 means array is not sorted.
        // If both any of x,y is zero means
        // array is not rotated.
        if (y == 1) {
            // Checking for last element with first.
            if (arr[n - 1] < arr[0])
                x++;
            else
                y++;
 
            // Checking for final result.
            if (y == 1)
                return true;
        }
        // If still not true then definitely false.
        return false;
    }
 
    // Driver code
        var arr = [ 5, 1, 2, 3, 4 ];
 
        var n = arr.length;
 
        // Function Call
        var x = checkIfSortRotated(arr, n);
        if (x == true)
            document.write("YES");
        else
            document.write("NO");
 
// This code is contributed by shivanisinghss2110


Python3




def checkRotatedAndSorted(arr, n):
 
    # Your code here
    # Initializing two variables x,y as zero.
    x = 0
    y = 0
 
    # Traversing array 0 to last element.
    # n-1 is taken as we used i+1.
    for i in range(n-1):
        if (arr[i] < arr[i + 1]):
            x += 1
        else:
            y += 1
 
    # If till now both x,y are greater than 1 means
    # array is not sorted. If both any of x,y is zero
    # means array is not rotated.
    if (y == 1):
        # Checking for last element with first.
        if (arr[n - 1] < arr[0]):
            x += 1
        else:
            y += 1
 
        # Checking for final result.
        if (y == 1):
            return True
 
    # If still not true then definitely false.
    return False
 
 
# Driver Code Starts.
arr = [4, 5, 1, 2, 3]
n = len(arr)
 
# Function Call
if (checkRotatedAndSorted(arr, n)):
    print("YES")
else:
    print("NO")
 
# This code is contributed by shivanisinghss2110


Output

YES

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 08 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads