dsa · easy
Find Peak Element
A **peak** is an index i whose value is **strictly greater** than both neighbors. Treat the neighbors of the ends as −∞: a length-1 array peaks at index 0, and [1,2] peaks at index 1 (2 > 1 and 2 > −∞).
Arguments
nums— the input array of integers
Equal neighbors are **not** a peak. Adjacent values are never equal, so a peak always exists. Return **any** peak index — if several exist, any of them is accepted.
Example
nums = [1, 2, 3, 1]
- index 0: 1 vs (only 2) → 1 < 2, not a peak
- index 1: 2 vs 1 and 3 → 2 < 3, not a peak
- index 2: 3 vs 2 and 1 → 3 > 2 and 3 > 1 → peak, return
2
[1, 2, 1, 3, 5, 6, 4] has peaks at 1 (value 2) and 5 (value 6); either index is correct.
Constraints
1 <= nums.length <= 4*10^4; nums[i] != nums[i+1]; a peak always exists Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.
Examples
Example 1
Input: [1,2,3,1] Expected: 2
Example 2
Input: [1] Expected: 0
Example 3
Input: [1,2,1,3,5,6,4] Expected: 5