Skip to content
ΣDSA Patterns
Menu
Language

Binary Search

Guide 5 of 6 · Path 5 of 6

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
2
3
1

any peak is ok

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

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

Binary search on a peak: always step toward the higher neighbor.

Reflection