#153
Find Minimum in Rotated Sorted Array
MediumArrayBinary SearchBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
By leveraging the properties of a rotated sorted array, we can use a binary search approach to find the minimum element efficiently in O(log n) time. We can determine which half of the array is sorted and decide which half to search next.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, left at 0 and right at the last index of the array.
- 2Step 2: While left is less than right, calculate the mid index.
- 3Step 3: If nums[mid] > nums[right], the minimum must be in the right half. Move left to mid + 1.
- 4Step 4: If nums[mid] <= nums[right], the minimum is in the left half or could be mid. Move right to mid.
- 5Step 5: When left equals right, return nums[left] as the minimum.
solution.py14 lines
1# Full working Python code
2
3def findMin(nums):
4 left, right = 0, len(nums) - 1
5 while left < right:
6 mid = (left + right) // 2
7 if nums[mid] > nums[right]:
8 left = mid + 1
9 else:
10 right = mid
11 return nums[left]
12
13# Example usage
14print(findMin([3,4,5,1,2])) # Output: 1ℹ
Complexity note: This complexity is O(log n) because we are halving the search space with each iteration, similar to binary search.
- 1The array is sorted but rotated, which means the minimum element is the point where the order breaks.
- 2Using binary search allows us to efficiently narrow down the search space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.