Given a circularly sorted integer array, search an element in it. 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]
target = 10
 
Output: Element found at index 2
 
 
Input:
 
nums = [9, 10, 2, 5, 6, 8]
target = 5
 
Output: Element found at index 3

Practice this problem

 
Related Posts:

Find the number of rotations in a circularly sorted array

 
A simple solution would be to run a linear search on the array and find the given element’s 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 know that the middle element always divides the array into two subarrays, and the target element can lie only in one of these subarrays. It is worth noticing that at least one of these subarrays will always be sorted. If the middle element happens to be the point of rotation (minimum element), then both left and right subarrays will be sorted, but in any case, one half (subarray) must be sorted. The idea is to 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

Java


Download  Run Code

Python


Download  Run Code

Output:

Element found at index 3

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