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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code