In this tutorial, we’ll discuss searching for a number in a sorted and rotated array. We’ll define the problem and provide an example to explain it.
After that, we’ll present an elegant approach to solving it.
2. Defining the Problem
Given an integer, , and a sorted rotated array, , consisting of distinct integers, our task is to find the element’s position whose value equals in . If there’s no such element, we return .
Let’s take a look at the following example:
Assume we want to find the following numbers in the given array:
- position = 0
- position = -1 (not found)
- position = 3
3. Binary Search Approach
3.1. Main Idea
The main idea is to use the binary search technique to find the position of in . If we’re currently looking at the value at position , we’ll encounter three different cases:
- : meaning that we found our target, and we return its position
- : it means we have to look for a bigger element, so we’ll check whether the leftmost element is greater than , and is less than or equal to the target . In this case, our target should come after the leftmost element. Thus, we might find it in the left part of the array. Otherwise, it should be on the right part.
- : it means we have to look for a smaller element. Therefore, we check whether the rightmost element is less than , and is greater than or equal to . If so, our target should come before the rightmost element. Hence, we can find it in the right part of . Otherwise, it should be on the left part.
In the end, if we finish the binary search and don’t return any value during the search, then our target doesn’t exist in . As a result, we return .
Let’s take a look at the implementation:
The implementation uses the exact ideas described in section 3.1.
The complexity of this algorithm is , where is the length of the given array . The reason behind this complexity is the same as the binary search complexity, where we keep dividing the given array each time into two halves and looking for the target in one of them.
This article presented the most efficient way to find an integer in a sorted rotated array. First, we provided an example of the problem. Then we gave an elegant approach to solving it and walked through its implementation.