Binary Search

Peak Index in a Mountain Array

LC
Practice this algorithm on LeetCode to reinforce your understanding.
Open Problem

Find the peak of a strictly increasing-then-decreasing array — O(log n) time · O(1) space

What does it solve?

A mountain array strictly increases to a single peak, then strictly decreases. Given one, find the index of the peak — the top of the mountain — without scanning every element.

Because the shape is predictable, comparing any element to its neighbor tells you instantly which side of the peak you're on — that's enough to binary search.

The core idea

// while the window has more than one index:
mid = (lo + hi) / 2
if a[mid] < a[mid+1]:
  // still climbing — peak is further right
  lo = mid + 1
else:
  // descending — peak is here or to the left
  hi = mid

Complexity

Time complexity
O(log n)

Binary search — the window halves every comparison, just like a sorted array.

Space complexity
O(1)

Just two pointers, lo and hi — no extra memory needed.


Examples & edge cases

Live animation
mid mid+1 kept (active window) eliminated this step peak
Step — of —
Window [lo..hi]
—
—
mid
—
—
Direction
—
—
Step
—
—
Select an example and press Play to start.
✓ Complete
Speed Medium

Step-by-step table

Step Window mid a[mid] a[mid+1] Decision

C++ implementation

peak_index_mountain_array.cpp
#include <bits/stdc++.h>
using namespace std;

int peakIndexInMountainArray(vector<int>& arr) {
    int lo = 0, hi = arr.size() - 1;

    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;

        if (arr[mid] < arr[mid + 1]) {
            // still climbing -> peak is to the right of mid
            lo = mid + 1;
        } else {
            // descending (or exactly at the peak) -> peak is mid or to the left
            hi = mid;
        }
    }
    return lo; // lo == hi, the peak index
}

int main() {
    vector<int> arr = {1, 3, 5, 4, 2};
    cout << "Peak index: " << peakIndexInMountainArray(arr) << "\n";
    return 0;
}

My Notes

📝 Notes ✅

▼
===== -->