DSA
Peak Index in a Mountain Array
Binary Search on the mountain's slope direction. O(log n) time, O(1) space.
You are given an integer mountain array arr of length n where values increase to a peak and then decrease.
Return the index of the peak element in O(log n) time.
Practice Link
Intuition#
At any index mid in the mountain, the slope tells you exactly where the peak is:
- arr[mid - 1] < arr[mid] — you're on the ascending side; peak is at mid or to the right.
- arr[mid] < arr[mid - 1] — you're on the descending side; peak is to the left.
Binary search on slope direction, always moving toward the peak.
Why low = 1 and high = n-2?
The first and last elements can never be the peak — the array is guaranteed to strictly increase then decrease, so the peak is always interior. Skipping the boundary indices avoids an out-of-bounds access when checking arr[mid - 1].
Solution — Binary Search#
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int n = arr.size();
int low = 1, high = n - 2;
int peak = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid - 1] <= arr[mid]) {
// ascending or flat: peak is here or to the right
peak = mid;
low = mid + 1;
} else {
// descending: peak is to the left
high = mid - 1;
}
}
return peak;
}
};
Time Complexity: O(log n)
Space Complexity: O(1)
Trace — arr = [0, 10, 5, 2]#
| Iteration | low | high | mid | arr[mid-1] ≤ arr[mid]? | Action |
|---|---|---|---|---|---|
| 1 | 1 | 2 | 1 | 0 ≤ 10 → true | peak=1, low=2 |
| 2 | 2 | 2 | 2 | 10 ≤ 5 → false | high=1 |
| — | 2 | 1 | — | low > high → exit |
Return peak = 1 ✓
Relation to Find Peak Element#
Both problems binary-search on slope direction, but they differ in guarantees:
| Peak Index in Mountain Array | Find Peak Element | |
|---|---|---|
| Array shape | Strictly up then strictly down | Any array, multiple peaks possible |
| Peak count | Exactly one | At least one (any valid peak ok) |
| Search space | [1, n-2] (interior only) | [0, n-1] |
| Boundary | First/last can never be peak | Any peak including boundaries valid |