InterviewPrepKit

Home / Coding / Binary Search

Find Peak Element

medium Original β†—
Solving tips
  • Binary search works on unsorted data here via the invariant 'a peak always exists in [lo, hi]' given the -inf borders.
  • Compare nums[mid] with nums[mid+1]: if rising (nums[mid] < nums[mid+1]) climb right (lo = mid+1), else a peak is at mid or left (hi = mid).
  • The lo < hi guard keeps mid+1 in range; comparing only the right neighbor avoids all four-case boundary special-casing.
  • O(log n) time, O(1) space; do not hunt the global max (that is the O(n) trap) since any peak is accepted.

Problem

A peak is an element strictly greater than both of its neighbors. Given an integer array nums where no two adjacent elements are equal, return the index of any peak. Treat the positions just outside the array as negative infinity, so the ends only need to beat their single inside neighbor.

Your algorithm must run in O(log n) time β€” which is surprising, because the array is not sorted.

Examples

  • Input: nums = [1, 2, 3, 1] β†’ Output: 2 (3 is greater than both neighbors 2 and 1.)
  • Input: nums = [1, 2, 1, 3, 5, 6, 4] β†’ Output: 5 (or 1) (Both index 1 (value 2) and index 5 (value 6) are peaks; either is accepted.)
  • Input: nums = [5] β†’ Output: 0 (A single element beats its two imaginary βˆ’βˆž neighbors.)

Constraints

  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i + 1] for every adjacent pair.
  • Required time complexity: O(log n).

Think about it first

Hint 1 Why must a peak always exist? Imagine walking uphill from any element β€” with βˆ’βˆž off both ends, can an "always rising" walk go on forever?
Hint 2 Compare `nums[mid]` with `nums[mid + 1]`. If the value is rising there (`nums[mid] < nums[mid + 1]`), can you guarantee a peak somewhere to the right of mid? What about when it's falling?
Hint 3 Binary search on the slope: while `lo < hi`, if `nums[mid] < nums[mid + 1]` the uphill direction guarantees a peak in `[mid + 1, hi]`, so `lo = mid + 1`; otherwise a peak lives in `[lo, mid]`, so `hi = mid`. The pointers converge on a peak.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.