Find Peak Element - Problem

A peak element is an element that is strictly greater than its neighbors.

Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in O(log n) time.

Input & Output

Example 1 — Basic Peak
$ Input: nums = [1,2,3,1]
Output: 2
💡 Note: Element 3 at index 2 is a peak because 3 > 2 and 3 > 1. This satisfies the peak condition.
Example 2 — Multiple Peaks
$ Input: nums = [1,2,1,3,5,6,4]
Output: 5
💡 Note: Element 6 at index 5 is a peak because 6 > 5 and 6 > 4. Index 1 (element 2) is also a peak, but we can return any peak.
Example 3 — Single Element
$ Input: nums = [1]
Output: 0
💡 Note: With only one element, it's automatically a peak since it has no neighbors to compare with.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -231 ≤ nums[i] ≤ 231 - 1
  • nums[i] != nums[i + 1] for all valid i

Visualization

Tap to expand
Find Peak Element Problem1231index 0index 1index 2index 3Peak condition: nums[2] = 3 > nums[1] = 2 and 3 > nums[3] = 1Output: 2 (index of peak element)
Understanding the Visualization
1
Input
Array [1,2,3,1] where we need to find peak
2
Process
Check each element against its neighbors
3
Output
Return index 2 where element 3 is peak
Key Takeaway
🎯 Key Insight: Use binary search by following slope direction - ascending slopes lead to peaks on the right, descending slopes have peaks on the left
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
62.0K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen