160. Find Peak Element
You are given an array of integers nums where no two neighboring values are equal. A peak is an element strictly greater than both of its neighbors; imagine the positions just outside the array hold negative infinity, so the first and last elements only have to beat their single real neighbor.
In this version the input is guaranteed to be unimodal: it strictly rises and then strictly falls (either part may be empty), so exactly one peak exists. Return the index of that peak.
A left-to-right scan works — but the guarantee is begging for an O(log n) answer.
Example 1:
Input: nums = [1, 2, 3, 1]
Output: 2
Explanation: The values climb 1 → 2 → 3 and then drop to 1, so the peak value 3 sits at index 2.
Example 2:
Input: nums = [6, 5, 4, 3, 2, 1]
Output: 0
Explanation: The array only falls, so the very first element is the peak (its imaginary left neighbor is negative infinity).
Constraints:
- 1 ≤ nums.length ≤ 10⁵
- -2³¹ ≤ nums[i] ≤ 2³¹ - 1
- nums[i] ≠ nums[i + 1] for every adjacent pair.
- nums strictly increases then strictly decreases (either side may be empty), so exactly one peak exists.
Hints:
A single left-to-right pass can stop at the first index i where nums[i] > nums[i + 1] — on the rising side that never happens, so the first drop marks the summit. If there is no drop at all, the last element is the peak.
For O(log n): look at the middle element and its right neighbor. If nums[mid] < nums[mid + 1] you are on the rising slope, so the peak lies strictly to the right; otherwise you are at or past the summit, so keep mid as a candidate and search left.
Maintain lo and hi with the invariant that the peak is always inside [lo, hi]; when lo == hi you have it. Comparing mid with mid + 1 is safe as long as hi starts at n - 1 and you only ever set lo = mid + 1 or hi = mid.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [1, 2, 3, 1]
Expected output: 2