DevPath

← All problems

Find a Peak Element

Medium binary-search · arrays

Description

An element is a peak if it is strictly greater than its neighbours. Return the index of any peak.

Constraints

1 <= n <= 100000; adjacent values differ

Examples

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

Output: 2

Hints (1)
  • Move toward the rising side; a peak is guaranteed on that side.

Solutions

Binary search toward the rising side. · Time O(log n) · Space O(1)

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

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

Create account