Problem Description
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. Given the sorted rotated array of unique elements, return the minimum element of this array. The solution must run in O(log n) time.
Key Insights
- The rotated sorted array consists of two sorted subarrays.
- A modified binary search can be used to locate the pivot point where the rotation occurs.
- By comparing the middle element to the rightmost element, we can decide which half of the array contains the minimum.
Space and Time Complexity
Time Complexity: O(log n) Space Complexity: O(1)
Solution
Use a binary search approach. Initialize two pointers, left and right, at the start and end of the array. While left is less than right, calculate the middle index. If the middle element is greater than the right element, then the minimum is in the right half, so move the left pointer to mid + 1; otherwise, the minimum must be in the left half including mid, so adjust the right pointer to mid. When the loop terminates, left equals right and points to the minimum element. This approach leverages the properties of the rotated sorted array to achieve logarithmic time complexity.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.