A peak is a number that is strictly bigger than the numbers right next to it. Pretend there is minus infinity just before the first element and just after the last one, so an end of the array only has to beat its one real neighbour.
Given an array nums where no two neighbours are equal, return the index of any peak. If there are several, any one of them is accepted. Your algorithm must run in O(log n) time.
Example 1
Input: nums = [1, 3, 8, 12, 9, 6, 2] Output: 3 Why: 12 is bigger than 8 and 9
2 more examples and the constraints
Example 2
Input: nums = [4, 1, 6, 2, 9, 3] Output: 2 Why: 6 beats 1 and 2; index 0 or 4 is also accepted
Example 3
Input: nums = [7] Output: 0 Why: both sides count as minus infinity
Constraints
- 1 ≤ length of nums ≤ 1,000
- Each value fits in a 32-bit signed integer: −2,147,483,648 to 2,147,483,647
nums[i] != nums[i + 1]for every valid i
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan for the first dropO(n)
- Binary search on the slopeO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 numbers | Verdict |
|---|---|---|---|
| Scan for the first drop | O(n) | Correct, but misses O(log n) | |
| Binary search on the slope | O(log n) | Best; about 10 comparisons |
n = length of nums.
Edge cases to test
- One element. [7] returns 0: both neighbours are minus infinity.
- Only climbing. [1, 2, 3, 4] has its peak at the last index, 3.
- Only falling. [9, 5, 2] has its peak at index 0.
- Extreme values. [−2,147,483,648, 2,147,483,647] has its peak at 1. Never use a sentinel like INT_MIN as a real neighbour.
- Many peaks. [4, 1, 6, 2, 9, 3] has three; any of 0, 2 or 4 is right.
Common mistakes
- Comparing with
nums[mid − 1]when mid can be 0, or withnums[mid + 1]when mid can be the last index. - Using
while lo <= hiwithhi = mid, which loops forever once lo equals hi. - Thinking binary search needs a sorted array; here it only needs a rule that tells which half still holds an answer.
How to talk through it
- 1Clarify. Can neighbours be equal? Is any peak fine? Do the ends count as peaks against the outside?
- 2Give the scan. Return the first drop. It is O(n), and the problem asks for O(log n).
- 3Argue the uphill rule. If mid is smaller than its right neighbour, walking right must reach a peak before the edge.
- 4Code the binary search. Use
lo < hiand compare mid with mid + 1 so the index is always valid. - 5Test out loud. Run one element, a pure climb, a pure fall and an array with several peaks.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?