Find Peak Element - Problem

Imagine you're hiking through a mountain range represented by an array of integers. A peak element is like a mountain summit - it's strictly higher than both its neighboring peaks. Your mission? Find any summit and return its position!

Given a 0-indexed integer array nums, find a peak element and return its index. If multiple peaks exist, you can return any of them. The array boundaries are considered to have value -โˆž, so elements at the edges only need to be greater than their single neighbor.

The Challenge: You must solve this in O(log n) time - no linear scanning allowed!

Example: In array [1,2,3,1], element 3 at index 2 is a peak because 3 > 2 and 3 > 1.

Input & Output

example_1.py โ€” 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 is the only peak in the array.
example_2.py โ€” Multiple Peaks
$ Input: nums = [1,2,1,3,5,6,4]
โ€บ Output: 5
๐Ÿ’ก Note: The array has peaks at indices 1 (value 2) and 5 (value 6). The algorithm can return either one, but typically returns 5 using binary search.
example_3.py โ€” Single Element
$ Input: nums = [1]
โ€บ Output: 0
๐Ÿ’ก Note: A single element is always considered 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
  • Follow up: Could you implement a solution with O(log n) time complexity?

Visualization

Tap to expand
๐Ÿš Mountain Peak Discovery๐Ÿ”๏ธ PEAKBinary Search Path๐Ÿ” Strategy: Follow the upward slopes, eliminate downward areas
Understanding the Visualization
1
Survey the Range
Start by looking at the middle of your mountain range
2
Follow the Slope
If the terrain is going uphill to your right, fly that direction - there must be a peak ahead
3
Eliminate Areas
Each decision eliminates half the mountain range from consideration
4
Converge on Peak
Continue until you find a summit that's higher than both sides
Key Takeaway
๐ŸŽฏ Key Insight: A peak always exists, and by following slope directions we can eliminate half the search space each time, achieving O(log n) efficiency!
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28 Apple 22
42.0K Views
High Frequency
~15 min Avg. Time
1.4K 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