Peak Index in a Mountain Array

Medium Binary Search

Problem

Given an array that strictly ascends then strictly descends, return the index of the peak.

Example 1 Input: [0,1,0] Output: 1
Example 2 Input: [0,2,1,0] Output: 1
Example 3 Input: [0,10,5,2] Output: 1

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def peakIndexInMountainArray(self, arr):
        lo, hi = 0, len(arr) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if arr[mid] < arr[mid + 1]:
                lo = mid + 1
            else:
                hi = mid
        return lo

Java

class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int lo = 0, hi = arr.length - 1;
        while (lo < hi) {
            int m = lo + (hi - lo) / 2;
            if (arr[m] < arr[m + 1]) lo = m + 1;
            else                      hi = m;
        }
        return lo;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Peak Index in a Mountain Array interactively → ← All solutions