Given a circularly sorted integer array, find the total number of times the array is rotated. Assume there are no duplicates in the array, and the rotation is in the anti-clockwise direction.

For example,

Input:  nums = [8, 9, 10, 2, 5, 6]
Output: The array is rotated 3 times
 
 
Input:  nums = [2, 5, 6, 8, 9, 10]
Output: The array is rotated 0 times

Practice this problem

If we carefully analyze the problem, we can see that the total number of rotations is equal to the total number of elements before the minimum element, or the index of the minimum element.

 
A simple solution would be to run a linear search on the array and find the minimum element index. The problem with this approach is that its worst-case time complexity is O(n), where n is the size of the input. This solution also does not take advantage of the fact that the input is circularly sorted.

 
We can easily solve this problem in O(log(n)) time by modifying the binary search algorithm. We have already reduced the problem to find out the first element of the sorted sequence. The first element (Pivot) has one special property (let’s call it the pivot’s property) – both the next and previous element of the pivot element are greater than it. No other array element will have this property except the pivot element. Since the array is circularly sorted,

  • If the pivot is the last element, then the first element will be considered its next element.
  • If the pivot is the first element, then the last element will be considered its previous element.

We know that the middle element always divides the array into two subarrays, and the pivot element can lie only in one of these halves. It is worth noticing that at least one of these subarrays will always be sorted. If middle element happens to be the point of rotation (minimum element), then both left and right subarrays are sorted. Still, in any case, one half (subarray) must be sorted, and we will use this property to discard the left half or the right half at each iteration of the binary search.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Array is rotated 3 times

Java


Download  Run Code

Output:

Array is rotated 3 times

Python


Download  Run Code

Output:

Array is rotated 3 times

The time complexity of the above solution is O(log(n)) and doesn’t require any extra space.