|
| 1 | +# Find Minimum in Rotated Sorted Array |
| 2 | + |
| 3 | +## Problem Description |
| 4 | + |
| 5 | +Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. |
| 6 | +(i.e., `[0,1,2,4,5,6,7]` might become `[4,5,6,7,0,1,2]`). |
| 7 | + |
| 8 | +Find the minimum element. |
| 9 | + |
| 10 | +You may assume no duplicate exists in the array. |
| 11 | + |
| 12 | +## Solution |
| 13 | + |
| 14 | +This problem can be solved efficiently using a modified binary search approach. |
| 15 | +The key idea is to observe that if we pick an arbitrary element `mid`, one of the two halves (left or right) must be sorted. |
| 16 | +The minimum element will always be in the unsorted half. |
| 17 | + |
| 18 | +1. Initialize `left` to 0 and `right` to `len(nums) - 1`. |
| 19 | +2. While `left < right`: |
| 20 | + a. Calculate `mid = left + (right - left) / 2`. |
| 21 | + b. If `nums[mid] > nums[right]`, it means the minimum element is in the right half (from `mid + 1` to `right`), because the right part is unsorted. So, set `left = mid + 1`. |
| 22 | + c. Else (`nums[mid] < nums[right]`), it means the minimum element is in the left half (from `left` to `mid`), because the right part is sorted, and `nums[mid]` could be the minimum. So, set `right = mid`. |
| 23 | +3. Return `nums[left]` (or `nums[right]`, as `left` and `right` will converge to the minimum element's index). |
| 24 | + |
| 25 | +## Code (GoLang) |
| 26 | + |
| 27 | +```go |
| 28 | +package main |
| 29 | + |
| 30 | +import "fmt" |
| 31 | + |
| 32 | +func findMin(nums []int) int { |
| 33 | + left, right := 0, len(nums)-1 |
| 34 | + |
| 35 | + for left < right { |
| 36 | + mid := left + (right-left)/2 |
| 37 | + if nums[mid] > nums[right] { |
| 38 | + // Minimum is in the right half (mid+1 to right) |
| 39 | + left = mid + 1 |
| 40 | + } else { |
| 41 | + // Minimum is in the left half (left to mid) |
| 42 | + // nums[mid] could be the minimum |
| 43 | + right = mid |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return nums[left] |
| 48 | +} |
| 49 | + |
| 50 | +func main() { |
| 51 | + fmt.Println(findMin([]int{3, 4, 5, 1, 2})) // Output: 1 |
| 52 | + fmt.Println(findMin([]int{4, 5, 6, 7, 0, 1, 2})) // Output: 0 |
| 53 | + fmt.Println(findMin([]int{1})) // Output: 1 |
| 54 | + fmt.Println(findMin([]int{1, 2})) // Output: 1 |
| 55 | + fmt.Println(findMin([]int{2, 1})) // Output: 1 |
| 56 | +} |
| 57 | +``` |
0 commit comments