Peak Index in a Mountain Array — LeetCode 852 Python Solution

MediumArrayBinary Search
Problem
#852
Reading time
2 min

The problem

You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease. Return the index of the peak element.

Python solution

Python
class Solution:
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        left, right = 1, len(arr) - 2
        while left < right:
            mid = (left + right) >> 1
            if arr[mid] > arr[mid + 1]:
                right = mid
            else:
                left = mid + 1
        return left

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 852. Peak Index in a Mountain Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 852. Peak Index in a Mountain Array?
LeetCode 852. Peak Index in a Mountain Array is rated Medium on LeetCode.
What topics does LeetCode 852. Peak Index in a Mountain Array cover?
LeetCode 852. Peak Index in a Mountain Array is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview