#162
Find Peak Element
MediumArrayBinary SearchBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
Using a binary search approach allows us to efficiently find a peak element in O(log n) time by leveraging the properties of peak elements.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers, left and right, to the start and end of the array.
- 2Step 2: While left is less than right, calculate the middle index.
- 3Step 3: Compare the middle element with its right neighbor. If it's less, move left to mid + 1; otherwise, move right to mid.
- 4Step 4: When left equals right, return the index as the peak element.
solution.py11 lines
1# Full working Python code
2
3def findPeakElement(nums):
4 left, right = 0, len(nums) - 1
5 while left < right:
6 mid = (left + right) // 2
7 if nums[mid] < nums[mid + 1]:
8 left = mid + 1
9 else:
10 right = mid
11 return leftℹ
Complexity note: This complexity is achieved by halving the search space with each iteration, similar to how binary search works.
- 1A peak can be found at the edges or in the middle of the array.
- 2Binary search can effectively reduce the search space for peak finding.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.