InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Find Peak Element

medium Original ↗ 00:00

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, even though 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? Start at any element and keep stepping toward a larger neighbor. With −∞ beyond both ends, this walk cannot continue forever, so it must stop at a peak.
Hint 2 Compare `nums[mid]` with `nums[mid + 1]`. If `nums[mid] < nums[mid + 1]`, is a peak guaranteed somewhere to the right of `mid`? What about when the value falls?
Hint 3 Binary search on the slope: while `lo < hi`, if `nums[mid] < nums[mid + 1]` a peak lies in `[mid + 1, hi]`, so set `lo = mid + 1`; otherwise a peak lies in `[lo, mid]`, so set `hi = mid`. The pointers converge on a peak.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug