sagelearnai

Find Peak Element

Difficulty: Medium · Pattern: Binary Search · LeetCode #162

A peak is an element strictly greater than its neighbors (out-of-range neighbors count as −∞). Adjacent elements are never equal. Return the index of any peak in O(log n).

Examples

text
[1, 2, 3, 1]           →  2
[1, 2, 1, 3, 5, 6, 4]  →  1 or 5

The tests accept any valid peak index.

Hints

  1. If nums[mid] < nums[mid + 1], you're on an upward slope: a peak exists to the right.
  2. Otherwise a peak exists at mid or to its left.

Approach

Binary search on the slope: if nums[mid] < nums[mid+1], set lo = mid + 1 (climbing right must eventually hit a peak, because the edge counts as −∞); else hi = mid. The loop ends at a peak. O(log n).

Complexity

Time: O(log n). Space: O(1).

Python solution
def findPeakElement(nums):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < nums[mid + 1]:
            lo = mid + 1
        else:
            hi = mid
    return lo
JavaScript solution
function findPeakElement(nums) {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) { const mid = (lo + hi) >> 1; if (nums[mid] < nums[mid + 1]) lo = mid + 1; else hi = mid; }
  return lo;
}