What does it solve?
A mountain array strictly rises then strictly falls. Find the index of the peak. A linear scan is O(N), but the slope lets binary search reach it in O(log N).
Key insight: compare a[mid] with its right neighbour a[mid+1]. If a[mid] < a[mid+1] you're on the ascending side, the peak is to the right, so lo = mid+1. Otherwise you're on the descending side (or at the peak), so hi = mid. When lo == hi, that's the summit → O(log N).
The core idea
lo=0, hi=n-1
while lo < hi:
mid=(lo+hi)/2
if a[mid] < a[mid+1]:
lo = mid+1 # uphill → go right
else:
hi = mid # downhill → go left
return lo
while lo < hi:
mid=(lo+hi)/2
if a[mid] < a[mid+1]:
lo = mid+1 # uphill → go right
else:
hi = mid # downhill → go left
return lo
Complexity
Time complexity
O(log N)
Each comparison of neighbours halves the search range. Same shape as the "find peak element" pattern.
Space complexity
O(1)
Two pointers. No recursion needed.
Examples & edge cases
Live animation — follow the slope to the summit
lo
mid
mid+1 neighbour
hi
peak
Mountain
Current step detail
lo = —
mid = —
hi = —
peak = —
Step — of —
a[mid]
—
midpoint height
a[mid+1]
—
right neighbour
slope
—
up / down
peak index
—
summit
Select an example and press Play to start.
✓ Done
SpeedMedium
Step-by-step table
| Step | lo | mid | hi | a[mid] | a[mid+1] | slope | action |
|---|
C++ implementation
peak_index_mountain.cpp
#include <bits/stdc++.h> using namespace std; // Index of the peak in a strictly increasing-then-decreasing array int peakIndexInMountainArray(vector<int>& a) { int lo = 0, hi = (int)a.size() - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (a[mid] < a[mid + 1]) lo = mid + 1; // ascending slope → peak is to the right else hi = mid; // descending (or at peak) → peak is here or left } return lo; // lo == hi == peak } int main() { vector<int> a = {0,2,4,3,1}; cout << peakIndexInMountainArray(a) << "\n"; // 2 return 0; }
My Notes
📝Notes✅
Practice this problem