Peak Index in a Mountain Array — LeetCode 852 Python Solution
- Problem
- #852
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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 leftComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(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.