Find Peak Element
Medium
Binary SearchArray
Problem
A peak is an index i with nums[i] > nums[i−1] and nums[i] > nums[i+1] (treating out-of-bounds as −∞). Return the index of any peak. Aim for O(log n).
Example 1
Input: nums = [1,2,3,1]
Output: 2
Example 2
Input: nums = [1,2,1,3,5,6,4]
Output: 5 or 1
Constraints
- 1 ≤ nums.length ≤ 1000
- nums[i] ≠ nums[i+1]
- −2³¹ ≤ nums[i] ≤ 2³¹−1
Approach — Binary Search
This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(log n) time.
Solution code
Python
class Solution:
def findPeakElement(self, nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo
Java
class Solution {
public int findPeakElement(int[] nums) {
int lo = 0, hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < nums[mid + 1]) lo = mid + 1;
else hi = mid;
}
return lo;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Find Peak Element interactively → ← All solutions