LC 852 Peak / Slope Medium

Peak Index in a Mountain Array

LC 162's simpler cousin — the array is guaranteed to be a mountain. Same slope logic, same template, cleaner guarantees.

What are we solving?

Problem Statement

An array arr is a mountain array if it strictly increases to a single peak then strictly decreases. Given such an array, return the index of the peak element. Must run in O(log n).

Example
Input:arr = [0, 1, 0]
Output:1
Example 2
Input:arr = [0, 2, 1, 0]
Output:1

First True: first point where descent begins

Because the array is a strict mountain, we can also frame this as a First True problem. The condition arr[i] > arr[i+1] is false on the ascending slope and true from the peak onwards.

arr = [1, 3, 5, 7, 6, 4, 2]
condition: arr[i] > arr[i+1]
1>3?F
3>5?F
5>7?F
7>6?T*
6>4?T
4>2?T
First T = index 3, value 7 = the peak. The last element has no next element — treat as T (imagine arr[n] = −∞).

vs LC 162: LC 162 has multiple peaks and uses the slope-following template. LC 852 has exactly one peak and can use either the slope template or the First True template — they give identical results on a strict mountain array.

Clean implementation

class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int left = 0, right = arr.length - 1;

        while (left < right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] < arr[mid + 1])
                left = mid + 1;  // still ascending — peak is to the right
            else
                right = mid;    // descending — peak is here or to the left
        }

        return left;
    }
}
class Solution:
    def peakIndexInMountainArray(self, arr: list[int]) -> int:
        left, right = 0, len(arr) - 1

        while left < right:
            mid = left + (right - left) // 2

            if arr[mid] < arr[mid + 1]:
                left = mid + 1   # still ascending
            else:
                right = mid      # descending or at peak

        return left

Complexity

Time
O(log n)
Halves the range each step using slope direction.
Space
O(1)
Constant — only two pointer variables.
↑ Pattern map