Find Peak Element — LeetCode 162 Python Solution

MediumArrayBinary Search
Problem
#162
Reading time
2 min

The problem

A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index.

Example

Input
nums = [1,2,3,1]
Output
2
Explanation
3 is a peak element and your function should return the index number 2.

Python solution

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

Complexity

MeasureComplexity
TimeO(\log n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 162. Find Peak Element 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

On study lists

This problem is on LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 162. Find Peak Element?
LeetCode 162. Find Peak Element is rated Medium on LeetCode.
What is the time complexity of LeetCode 162. Find Peak Element?
The Python solution on this page runs in O(\log n), where n is the length of the array nums.
What is the space complexity of LeetCode 162. Find Peak Element?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 162. Find Peak Element cover?
LeetCode 162. Find Peak Element 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