Skip to content
ΣDSA Patterns
Menu
Language

Binary Search

Guide 5 of 6 · Path 5 of 6

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

Tested only
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;
}

Reflection