DevPath

← All problems

Minimum in Rotated Sorted Array

Medium binary-search · arrays

Description

A sorted array was rotated at some pivot. Return the minimum value.

Constraints

1 <= n <= 100000; values are distinct

Examples

Input: nums = [3,4,5,1,2]

Output: 1

Hints (1)
  • Compare the middle value with the right end to decide which half holds the minimum.

Solutions

Binary search against the right end. · Time O(log n) · Space O(1)

func findMin(nums []int) int {
    lo, hi := 0, len(nums)-1
    for lo < hi {
        mid := (lo + hi) / 2
        if nums[mid] > nums[hi] {
            lo = mid + 1
        } else {
            hi = mid
        }
    }
    return nums[lo]
}

Create a free account to submit solutions, track progress and save problems.

Create account