Find Minimum in Rotated Sorted List in Python
Uses binary search to find the minimum element in a rotated sorted list in O(log n) time.
Python code
14 linesdef find_min(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
if __name__ == "__main__":
rotated = [4, 5, 6, 7, 0, 1, 2]
print(f"Minimum: {find_min(rotated)}")
Output
Minimum: 0
How it works
The algorithm leverages the property of a rotated sorted array: there is exactly one point where the order breaks. By comparing the middle element to the rightmost element, we can determine which half contains the minimum. If the middle is greater than the rightmost, the minimum lies in the right half; otherwise, it is in the left half (including mid). This halves the search space each iteration until left and right converge to the index of the minimum, achieving O(log n) time.
Common mistakes
- Using mid = (left + right) // 2 with left < right might cause infinite loops if not updating left correctly
- Comparing mid with left instead of right can fail on certain rotations
- Forgetting that the list can contain duplicates, which could break the comparison logic
- Assuming the list is always rotated; the algorithm should also work for a fully sorted list
Variations
- Use recursion instead of iteration to implement binary search
- Use Python's built-in min() if O(n) time is acceptable
- Handle duplicates by adding linear scans when mid equals right
Real-world use cases
- Finding the smallest version number in a circular release history list
- Locating the earliest timestamp in a periodically rotated log offset list
- Identifying the minimum value in a circularly sorted signal array for anomaly detection
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.