Find any peak element in an array where values are strictly greater than their neighbors.
Find Peak Element
Given an integer array nums, return the index of any peak element.
An element is a peak if it is strictly greater than its adjacent elements. For the boundaries, treat the element outside the array as negative infinity.
You may assume that:
nums[-1] = nums[n] = -∞- there is always at least one peak element
Your goal is to return the index of any peak element in O(log n) time.
Input Format
- A single integer array
nums. numscontains at least one element.
Output Format
- Return an integer index of any peak element.
Constraints
- Adjacent elements are treated with strict comparison for peak detection.
- Assume a peak always exists.
Example 1
Input
nums = [1,2,3,1]
Output
2
Explanation
nums[2] = 3 is greater than both neighbors, so index 2 is a peak.
Example 2
Input
nums = [1,2,1,3,5,6,4]
Output
1
Explanation
Index 1 is a valid peak because 2 > 1 and 2 > 1. Index 5 is also a peak, so either answer is acceptable.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.