Problem
Suppose an array of length n
sorted in ascending order is rotated between 1
and n
times. For example, the array nums = [0,1,2,4,5,6,7]
might become:
[4,5,6,7,0,1,2]
if it was rotated4
times.[0,1,2,4,5,6,7]
if it was rotated7
times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array nums
of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time
.
Example
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
The answer to this lies on the fact that if we can find the point on inflection and things will be simple. So if we can have 2 sub arrays A and B,
If we pick the middle element, we can compare the middle element with the leftmost (or rightmost) element. If the middle element is less than leftmost, the left half should be selected; if the middle element is greater than the leftmost (or rightmost), the right half should be selected. Using recursion or iteration, this problem can be solved in time log(n).
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Naive Linear search
A naive approach is to iterate through the array linearly, comparing each element with the current minimum, and updating the minimum whenever a smaller value is found.
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Method 2 - Recursive Binary Search
Define a helper function, otherwise, we will need to use Arrays.copyOfRange() function, which may be expensive for large arrays.
We use a binary search approach since the rotated sorted array retains partial properties of a sorted array:
- Divide the array into two halves.
- Compare the middle element (
mid
) with the rightmost (right
) element to determine which half to search next:- If
a[mid] > a[right]
, the smallest element lies in the right half. - If
a[mid] ≤ a[right]
, the smallest element lies in the left half (includingmid
itself).
- If
This approach ensures that we reduce the search space logarithmically.
Key points:
- A rotated sorted array has at least one section that is sorted.
- The minimum element breaks the sorted sequence, making it an ideal target for binary search.
- The key observation is to compare values at
mid
andright
positions during each iteration.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(log n)
Method 3 - Iterative Solution
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)