Data Structures & Algorithms Binary Search
💡
Exercise 51

Min in Rotated Array 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

A sorted array has been rotated between 1 and n times. For example, [0,1,2,4,5,6,7] rotated 4 times becomes [4,5,6,7,0,1,2].

Find the minimum element. You must write an O(log n) algorithm.

nums = [3,4,5,1,2] → 1 nums = [4,5,6,7,0,1,2] → 0

Binary search trick: compare nums[mid] with nums[right]. If mid > right, the minimum is in the right half. Otherwise, it's in the left half (including mid).

📋 Instructions
Implement `find_min(nums)` for a rotated sorted array. Test with `[3,4,5,1,2]` and `[4,5,6,7,0,1,2]`. Print both results.
left=0, right=len-1. While left < right: if nums[mid] > nums[right], min is in [mid+1, right]. Else min is in [left, mid]. Return nums[left].
🧪 Test Cases
Input
find_min([3,4,5,1,2])
Expected
1
Test case 1
Input
find_min([4,5,6,7,0,1,2])
Expected
0
Boundary value
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.