Peak Index in a Mountain Array - Problem
You are given a mountain array - a special type of array where values strictly increase to reach a peak element, then strictly decrease afterward. Think of it like a mountain profile!
A mountain array
โข
โข There exists some index
-
-
Your mission: Find the index of the peak element in
Example: In array
A mountain array
arr satisfies these conditions:โข
arr.length >= 3โข There exists some index
i (the peak) where:-
arr[0] < arr[1] < ... < arr[i-1] < arr[i] (strictly increasing)-
arr[i] > arr[i+1] > ... > arr[arr.length-1] (strictly decreasing)Your mission: Find the index of the peak element in
O(log n) time complexity. The peak is guaranteed to exist and is never at the first or last position.Example: In array
[1, 3, 8, 12, 4, 2], the peak is 12 at index 3. Input & Output
example_1.py โ Basic Mountain
$
Input:
[0, 1, 0]
โบ
Output:
1
๐ก Note:
The peak element is 1 at index 1. This is the simplest mountain with 3 elements.
example_2.py โ Larger Mountain
$
Input:
[0, 2, 1, 0]
โบ
Output:
1
๐ก Note:
The peak element is 2 at index 1. The array increases to 2, then decreases.
example_3.py โ Complex Mountain
$
Input:
[0, 10, 5, 2]
โบ
Output:
1
๐ก Note:
The peak element is 10 at index 1. Even with larger values, the peak principle remains the same.
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Range
Start with the entire mountain range in view
2
Check Middle Point
Fly to the middle and check if you're going uphill or downhill
3
Eliminate Half
Based on the slope, eliminate half the mountain from search
4
Repeat Process
Continue narrowing down until you find the peak
Key Takeaway
๐ฏ Key Insight: Binary search works because a mountain array has a unique property - at any position, we can determine which side the peak is on by comparing adjacent elements, allowing us to eliminate half the search space each time!
Time & Space Complexity
Time Complexity
O(log n)
Each iteration eliminates half the remaining elements, leading to log n iterations
โก Linearithmic
Space Complexity
O(1)
Only using constant extra space for left, right, and mid pointers
โ Linear Space
Constraints
- 3 โค arr.length โค 104
- 0 โค arr[i] โค 106
- arr is guaranteed to be a mountain array
- The peak is never at index 0 or arr.length - 1
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code