MediumNo. 0162
Find Peak Element — LeetCode 162 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search
- On study lists
- LeetCode 75 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
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
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 leftComplexity
- Time
- O(log n)where n is the length of the array nums
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0154 | Find Minimum in Rotated Sorted Array II | Hard |
| 0153 | Find Minimum in Rotated Sorted Array | Medium |
| 0004 | Median of Two Sorted Arrays | Hard |
| 0033 | Search in Rotated Sorted Array | Medium |
| 0034 | Find First and Last Position of Element in Sorted Array | Medium |
| 0035 | Search Insert Position | Easy |
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.