Skip to content
DSA Patterns
Menu
Language
Binary SearchLC #1625 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Find Peak Element

Problem (restated)

Return any peak index (strictly greater than neighbors). nums[-1]=nums[n]=-∞.

Intuition

Ascending mid → peak on the right; else peak on left/mid.

Approaches

Binary search on slope

Unverified
Time O(log n)Space O(1)

Idea. If nums[mid] < nums[mid+1], lo=mid+1; else hi=mid.

Walkthrough. [1,2,3,1] → peak at index 2.

Trade-offs. Linear max is simpler but not O(log n).

Solution
export function findPeakElement(nums: number[]): number {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (nums[mid]! < nums[mid + 1]!) lo = mid + 1; else hi = mid;
  }
  return lo;
}
export function findPeakElement(nums: number[]): number {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (nums[mid]! < nums[mid + 1]!) lo = mid + 1; else hi = mid;
  }
  return lo;
}

Template connection

If nums[mid] < nums[mid + 1], a peak sits to the right, so lo becomes mid + 1. Otherwise a peak sits at mid or to the left. Neighbors outside the array count as smaller, so an endpoint can be the peak.

Reflection

  • If nums[mid] < nums[mid + 1], a peak is on the right. Any peak is enough. Why is the search still O(log n)?
  • The ends are treated as negative infinity. Does that make index 0 or n - 1 a legal peak?
  • Neighbors are never equal. What breaks if a neighbor can tie nums[mid]?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Peak: strictly greater than neighbors. Sentinels nums[-1]=nums[n]=−∞.

1
0
2
1
3
2
1
3

any peak is ok

Key:CurrentActive rangeMatchSettledEliminated