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 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
Mountain Peak Discovery with Binary SearchPEAK๐Ÿš HelicopterEliminated (Left Half)Eliminated (Right Half)Active Search Area๐ŸŽฏ Key Insight: At any point, we can determine which half contains the peakby checking if we're going uphill (peak to the right) or downhill (peak to the left)
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

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using constant extra space for left, right, and mid pointers

n
2n
โœ“ 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
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
89.7K Views
High Frequency
~15 min Avg. Time
2.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