Find Peak Element Solution
Find any index i such that nums[i] is strictly greater than its neighbours. Return its index.
Problem Statement
A peak element is strictly greater than its neighbours. Given an integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index of any peak. You may imagine that nums[-1] = nums[n] = -โ. You must write an O(log n) algorithm.
Linear Scan โ O(n)
Walk through the array. Return the first index where nums[i] > nums[i+1] โ that element is a peak (it's already greater than nums[i-1] because we came from an ascending sequence).
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(1) |
Binary Search โ O(log n)
Compare nums[mid] to nums[mid + 1]. If mid is on an ascending slope (nums[mid] < nums[mid+1]), a peak must exist to the right. If mid is descending, a peak must exist to the left (or mid itself). Move toward the higher side.
- Step 1:
left = 0,right = n - 1. - Step 2: While
left < right: - Step 3: If
nums[mid] < nums[mid + 1]โ ascending โ peak is right:left = mid + 1. - Step 4: Else โ descending โ peak is left or at mid:
right = mid. - Step 5: Return
left.
- Since
nums[-1] = nums[n] = -โ, if you follow an ascending slope, it must eventually descend (boundary is -โ). - The transition from ascending to descending is a peak. Binary search finds it by always moving uphill.
Visual Walkthrough
Trace through nums = [1, 2, 1, 3, 5, 6, 4]:
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Linear Scan | O(n) | O(1) | Finds first descent point |
| Binary Search โ optimal | O(log n) | O(1) | Move uphill โ peak guaranteed by -โ boundaries |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Single element | [1] | Always a peak (both neighbours are -โ). L==R==0. |
| Ascending | [1,2,3,4] | Peak is at the end (index 3). Binary search goes right every time. |
| Descending | [4,3,2,1] | Peak is at the start (index 0). Binary search goes left every time. |
| Multiple peaks | [1,3,1,5,1] | Return any peak โ both index 1 and 3 are valid. |
nums[mid] to nums[mid - 1] instead of nums[mid + 1]. When mid = 0, accessing nums[-1] is out of bounds. Comparing to mid + 1 is safe because the loop condition left < right ensures mid < right โค n-1, so mid + 1 is always valid.