Find the Rotation Count in Rotated Sorted array - GeeksforGeeks

30 Mar, 2022
Consider an array arr of distinct numbers sorted in increasing order. Given that this array has been rotated (clockwise) k number of times. Given such an array, find the value of k.
Examples:  
Input: arr[] = {15, 18, 2, 3, 6, 12}Output: 2Explanation: Initial array must be {2, 3, 6, 12, 15, 18}. We get the given array after rotating the initial array twice.
Input: arr[] = {7, 9, 11, 12, 5}Output: 4
Input: arr[] = {7, 9, 11, 12, 15};Output: 0
Method 1 (Using linear search)If we take closer look at examples, we can notice that the number of rotations is equal to index of minimum element. A simple linear solution is to find minimum element and returns its index. Below is C++ implementation of the idea.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of rotations// in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedint countRotations(int arr[], int n){    // We basically find index of minimum    // element    int min = arr[0], min_index;    for (int i=0; i<n; i++)    {        if (min > arr[i])        {            min = arr[i];            min_index = i;        }    }    return min_index;} // Driver codeint main(){    int arr[] = {15, 18, 2, 3, 6, 12};    int n = sizeof(arr)/sizeof(arr[0]);    cout << countRotations(arr, n);    return 0;}
// Java program to find number of// rotations in a sorted and rotated// array.import java.util.*;import java.lang.*;import java.io.*; class LinearSearch{    // Returns count of rotations for an    // array which is first sorted in    // ascending order, then rotated    static int countRotations(int arr[], int n)    {        // We basically find index of minimum        // element        int min = arr[0], min_index = -1;        for (int i = 0; i < n; i++)        {            if (min > arr[i])            {                min = arr[i];                min_index = i;            }        }        return min_index;    }     // Driver program to test above functions    public static void main (String[] args)    {        int arr[] = {15, 18, 2, 3, 6, 12};        int n = arr.length;             System.out.println(countRotations(arr, n));    }}// This code is contributed by Chhavi
# Python3 program to find number# of rotations in a sorted and# rotated array. # Returns count of rotations for# an array which is first sorted# in ascending order, then rotateddef countRotations(arr, n):     # We basically find index    # of minimum element    min = arr[0]    for i in range(0, n):             if (min > arr[i]):                     min = arr[i]            min_index = i             return min_index;  # Driver codearr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr, n)) # This code is contributed by Smitha Dinesh Semwal
// c# program to find number of// rotations in a sorted and rotated// array.using System; class LinearSearch{    // Returns count of rotations for an    // array which is first sorted in    // ascending order, then rotated    static int countRotations(int []arr, int n)    {        // We basically find index of minimum        // element        int min = arr[0], min_index = -1;        for (int i = 0; i < n; i++)        {            if (min > arr[i])            {                min = arr[i];                min_index = i;            }        }        return min_index;    }     // Driver program to test above functions    public static void Main ()    {        int []arr = {15, 18, 2, 3, 6, 12};        int n = arr.Length;         Console.WriteLine(countRotations(arr, n));    }}// This code is contributed by vt_m.
<?php// PHP program to find number// of rotations in a sorted// and rotated array. // Returns count of rotations// for an array which is first// sorted in ascending order,// then rotatedfunction countRotations($arr, $n){    // We basically find index    // of minimum element    $min = $arr[0];    $min_index;    for ($i = 0; $i < $n; $i++)    {        if ($min > $arr[$i])        {            $min = $arr[$i];            $min_index = $i;        }    }    return $min_index;} // Driver code$arr = array(15, 18, 2,             3, 6, 12);$n = sizeof($arr);echo countRotations($arr, $n); // This code is contributed// by ajit?>
<script> // Javascript program to find number of rotations// in a sorted and rotated array. // Returns count of rotations for an array which// is first sorted in ascending order, then rotated      function countRotations(arr, n)    {        // We basically find index of minimum        // element        let min = arr[0], min_index = -1;        for (let i = 0; i < n; i++)        {            if (min > arr[i])            {                min = arr[i];                min_index = i;            }        }        return min_index;    } // Driver Code         let arr = [15, 18, 2, 3, 6, 12];    let n = arr.length;         document.write(countRotations(arr, n)); </script>
2
Time Complexity : O(n) Auxiliary Space : O(1) 
Method 2 (Efficient Using Binary Search) Here also we find the index of minimum element, but using Binary Search. The idea is based on the below facts :  
The minimum element is the only element whose previous is greater than it. If there is no previous element, then there is no rotation (first element is minimum). We check this condition for middle element by comparing it with (mid-1)’th and (mid+1)’th elements.
If the minimum element is not at the middle (neither mid nor mid + 1), then minimum element lies in either left half or right half. If middle element is smaller than last element, then the minimum element lies in left halfElse minimum element lies in right half.
If middle element is smaller than last element, then the minimum element lies in left halfElse minimum element lies in right half.
If middle element is smaller than last element, then the minimum element lies in left half
Else minimum element lies in right half.
Below is the implementation taken from here.  
C++
Java
Python3
C#
PHP
Javascript
// Binary Search based C++ program to find number// of rotations in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedint countRotations(int arr[], int low, int high){    // This condition is needed to handle the case    // when the array is not rotated at all    if (high < low)        return 0;     // If there is only one element left    if (high == low)        return low;     // Find mid    int mid = low + (high - low)/2; /*(low + high)/2;*/     // Check if element (mid+1) is minimum element.    // Consider the cases like {3, 4, 5, 1, 2}    if (mid < high && arr[mid+1] < arr[mid])       return (mid+1);     // Check if mid itself is minimum element    if (mid > low && arr[mid] < arr[mid - 1])       return mid;     // Decide whether we need to go to left half or    // right half    if (arr[high] > arr[mid])       return countRotations(arr, low, mid-1);     return countRotations(arr, mid+1, high);} // Driver codeint main(){    int arr[] = {15, 18, 2, 3, 6, 12};    int n = sizeof(arr)/sizeof(arr[0]);    cout << countRotations(arr, 0, n-1);    return 0;}
// Java program to find number of// rotations in a sorted and rotated// array.import java.util.*;import java.lang.*;import java.io.*; class BinarySearch{    // Returns count of rotations for an array    // which is first sorted in ascending order,    // then rotated    static int countRotations(int arr[], int low,                                       int high)    {        // This condition is needed to handle        // the case when array is not rotated        // at all        if (high < low)            return 0;         // If there is only one element left        if (high == low)            return low;         // Find mid        // /*(low + high)/2;*/        int mid = low + (high - low)/2;         // Check if element (mid+1) is minimum        // element. Consider the cases like        // {3, 4, 5, 1, 2}        if (mid < high && arr[mid+1] < arr[mid])            return (mid + 1);         // Check if mid itself is minimum element        if (mid > low && arr[mid] < arr[mid - 1])            return mid;         // Decide whether we need to go to left        // half or right half        if (arr[high] > arr[mid])            return countRotations(arr, low, mid - 1);         return countRotations(arr, mid + 1, high);    }     // Driver program to test above functions    public static void main (String[] args)    {        int arr[] = {15, 18, 2, 3, 6, 12};        int n = arr.length;                 System.out.println(countRotations(arr, 0, n-1));    }}// This code is contributed by Chhavi
# Binary Search based Python3# program to find number of# rotations in a sorted and# rotated array. # Returns count of rotations for# an array which is first sorted# in ascending order, then rotated def countRotations(arr):    n = len(arr)    start = 0    end = n-1     # Finding the index of minimum of the array    # index of min would be equal to number to rotation    while start<=end:        mid = start+(end-start)//2                 # Calculating the previous(prev)        # and next(nex) index of mid        prev = (mid-1+n)%n        nex = (mid+1)%n         # Checking if mid is minimum        if arr[mid]<arr[prev]\           and arr[mid]<=arr[nex]:          return mid               # if not selecting the unsorted part of array        elif arr[mid]<arr[start]: end = mid-1        elif arr[mid]>arr[end]: start = mid+1        else: return 0 # Driver codearr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find number of// rotations in a sorted and rotated// array.using System; class BinarySearch{    // Returns count of rotations for an array    // which is first sorted in ascending order,    // then rotated    static int countRotations(int []arr, int low, int high)    {        // This condition is needed to handle        // the case when array is not rotated        // at all        if (high < low)            return 0;         // If there is only one element left        if (high == low)            return low;         // Find mid        // /*(low + high)/2;*/        int mid = low + (high - low)/2;         // Check if element (mid+1) is minimum        // element. Consider the cases like        // {3, 4, 5, 1, 2}        if (mid < high && arr[mid+1] < arr[mid])            return (mid + 1);         // Check if mid itself is minimum element        if (mid > low && arr[mid] < arr[mid - 1])            return mid;         // Decide whether we need to go to left        // half or right half        if (arr[high] > arr[mid])            return countRotations(arr, low, mid - 1);         return countRotations(arr, mid + 1, high);    }     // Driver program to test above functions    public static void Main ()    {        int []arr = {15, 18, 2, 3, 6, 12};        int n = arr.Length;             Console.WriteLine(countRotations(arr, 0, n-1));    }}// This code is contributed by vt_m.
<?php// Binary Search based PHP// program to find number// of rotations in a sorted// and rotated array. // Returns count of rotations// for an array which is// first sorted in ascending// order, then rotatedfunction countRotations($arr,                        $low, $high){    // This condition is needed    // to handle the case when    // array is not rotated at all    if ($high < $low)        return 0;     // If there is only    // one element left    if ($high == $low)        return $low;     // Find mid    $mid = $low + ($high -                   $low) / 2;     // Check if element (mid+1)    // is minimum element. Consider    // the cases like {3, 4, 5, 1, 2}    if ($mid < $high &&        $arr[$mid + 1] < $arr[$mid])    return (int)($mid + 1);     // Check if mid itself    // is minimum element    if ($mid > $low &&        $arr[$mid] < $arr[$mid - 1])    return (int)($mid);     // Decide whether we need    // to go to left half or    // right half    if ($arr[$high] > $arr[$mid])    return countRotations($arr, $low,                          $mid - 1);     return countRotations($arr,                          $mid + 1,                          $high);} // Driver code$arr = array(15, 18, 2, 3, 6, 12);$n = sizeof($arr);echo countRotations($arr, 0, $n - 1); // This code is contributed bu ajit?>
<script>// Binary Search based C++ program to find number// of rotations in a sorted and rotated array. // Returns count of rotations for an array which// is first sorted in ascending order, then rotatedfunction countRotations(arr, low, high){    // This condition is needed to handle the case    // when the array is not rotated at all    if (high < low)        return 0;     // If there is only one element left    if (high == low)        return low;     // Find mid    let mid = Math.floor(low + (high - low)/2); /*(low + high)/2;*/     // Check if element (mid+1) is minimum element.    // Consider the cases like {3, 4, 5, 1, 2}    if (mid < high && arr[mid+1] < arr[mid])    return (mid+1);     // Check if mid itself is minimum element    if (mid > low && arr[mid] < arr[mid - 1])    return mid;     // Decide whether we need to go to left half or    // right half    if (arr[high] > arr[mid])    return countRotations(arr, low, mid-1);     return countRotations(arr, mid+1, high);} // Driver code    let arr = [15, 18, 2, 3, 6, 12];    let n = arr.length;    document.write(countRotations(arr, 0, n-1));    // This code is contributed by Surbhi Tyagi.</script>
2
Time Complexity : O(Log n) Auxiliary Space : O(Log n) 
Method 3: Iterative Code (Binary Search)
C++
Python3
Javascript
#include <bits/stdc++.h>using namespace std; // Returns count of rotations// for an array which is first sorted// in ascending order, then rotated // Observation: We have to return// index of the smallest elementint countRotations(int arr[], int n){    int low = 0, high = n - 1;    while (low <= high) {         // if first element is mid or        // last element is mid        // then simply use modulo so it        // never goes out of bound.        int mid = low + (high - low) / 2;        int prev = (mid - 1 + n) % n;        int next = (mid + 1) % n;         if (arr[mid] <= arr[prev]            && arr[mid] <= arr[next])            return mid;        else if (arr[mid] <= arr[high])            high = mid - 1;        else if (arr[mid] >= arr[low])            low = mid + 1;    }    return 0;} // Driver codeint main(){    int arr[] = { 15, 18, 2, 3, 6, 12 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << countRotations(arr, n);    return 0;}
# Returns count of rotations for an array which# is first sorted in ascending order, then rotated # Observation: We have to return index of the smallest elementdef countRotations(arr, n):     low = 0    high = n - 1    while(low<=high):               # if first element is mid or        # last element is mid        # then simply use modulo        # so it never goes out of bound.        mid = low + ((high - low) // 2)        prev = (mid - 1 + n) % n        next = (mid + 1) % n                 if(arr[mid] <= arr[prev] \           and arr[mid] <= arr[next]):            return mid        elif (arr[mid] <= arr[high]):            high = mid - 1        elif (arr[mid] >= arr[low]):            low = mid + 1    return 0 # Driver code arr = [15, 18, 2, 3, 6, 12]n = len(arr)print(countRotations(arr, n))    # This code is contributed by shinjanpatra.
<script> // Returns count of rotations for an array which// is first sorted in ascending order, then rotated //Observation: We have to return index of the smallest elementfunction countRotations(arr, n){           let low =0 , high = n-1;      while(low<=high){          let mid = low + Math.floor((high-low)/2) ;          let prev = (mid-1 + n)  %n , next = (mid+1)%n;//if first element is mid or        //last element is mid then simply use modulo so it never goes out of bound.          if(arr[mid]<=arr[prev] && arr[mid]<=arr[next])            return mid;          else if (arr[mid]<=arr[high])            high = mid-1 ;          else if (arr[mid]>=arr[low])            low=mid+1;      }      return 0;} // Driver code let arr = [15, 18, 2, 3, 6, 12];let n = arr.length;document.write(countRotations(arr, n));    // This code is contributed by shinjanpatra.</script>
2
Time Complexity : O(Log n)Auxiliary Space : O(1)
YouTubeGeeksforGeeks501K subscribersFind the Rotation Count in Rotated Sorted array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qHGpfJPQ0xY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
komal27
jit_t
_je_raj3sh
code_hunt
surbhityagi15
dishamangla9255
simmytarika5
jaiswalshruti1102
kavitarawat1
shinjanpatra
RishabhPrabhu
ABCO
Amazon
Binary Search
rotation
Arrays
Divide and Conquer
Amazon
ABCO
Arrays
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Merge Sort
QuickSort
Binary Search
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction