Find Peak Element solution explained
Find Peak Element is a binary search on the slope. Look at the middle value and its right neighbor: if the array is rising there, a peak must exist to the right, so move right; if it is falling, a peak exists at the middle or to its left, so move left. Each step halves the range, giving O(log n) time, even though the array is not sorted.
By Evin JohnPublished 7 min read
The problem, reworded
You get a list of numbers where no two neighbors are equal. A peak is a position whose value is greater than the value on each side. The first and last positions have only one real neighbor; pretend there is an infinitely low value beyond each end, so the first element is a peak if it beats the second, and the last is a peak if it beats the one before it. Return the index of any peak.
| Array | Peaks | Binary search returns |
|---|---|---|
[1, 4, 6, 5, 2, 7, 3] | Index 2 (6) and index 5 (7) | 2 |
[5, 1, 6, 2, 8, 0] | Indexes 0, 2 and 4 | 2 (a left-to-right scan would return 0) |
[9, 7, 4] | Index 0, since only one side is real | 0 |
[2, 5, 8] | Index 2, the last element | 2 |
[3] | Index 0 | 0 |
The second row is the point to make early: when several peaks exist, any of them is accepted, and different correct methods return different ones. Confirm that with the interviewer, along with the guarantee that neighbors are never equal. That guarantee is what makes the fast method work.
Why it is asked
Most people learn binary search as looking for a value in sorted data. This problem checks whether you understand what binary search really needs: a way to discard half the range while keeping at least one answer in the other half. Candidates who can state that invariant usually handle rotated arrays, search answers in a range of values, and other twists without memorizing each one.
Linear scan: find the first drop
Walk from the left. The first time a value is bigger than the next one, that value is a peak: it beats the next value, and it beats the previous one because the array was rising until here. If the values never drop, the last element is the peak. This is O(n) and is a perfectly sensible first answer.
def peak_index_slow(nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return i # first place the values stop rising
return len(nums) - 1Binary search on the slope
Pick a middle index mid and compare nums[mid] with nums[mid + 1]. Suppose the right neighbor is bigger, so the array climbs there. Keep walking right from mid + 1: either the values eventually drop, and the spot right before the drop is a peak, or they keep climbing to the end, and the last element is a peak because the imaginary value beyond it is lower. Either way, a peak exists at mid + 1 or later. If instead nums[mid] is bigger, the same argument run leftward shows a peak exists at mid or earlier.
So keep a range [lo, hi] that always contains a peak, and shrink it toward the uphill side. When lo equals hi, the range holds one index, and it must be a peak.
def peak_index(nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1 # rising here, so a peak lies to the right
else:
hi = mid # falling here, so mid or something left is a peak
return lofunction peakIndex(nums) {
let lo = 0;
let hi = nums.length - 1;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (nums[mid] < nums[mid + 1]) lo = mid + 1;
else hi = mid;
}
return lo;
}Trace on [5, 1, 6, 2, 8, 0]
| lo | hi | mid | nums[mid] vs nums[mid + 1] | Move |
|---|---|---|---|---|
| 0 | 5 | 2 | 6 vs 2, falling | hi = 2 |
| 0 | 2 | 1 | 1 vs 6, rising | lo = 2 |
| 2 | 2 | Stop: index 2 (value 6) is a peak |
Two details keep the loop safe. The condition lo < hi guarantees mid + 1 never runs past hi, so the comparison never reads outside the array. And setting hi = mid, not mid - 1, keeps mid in the range, which is required because mid itself may be the peak. That pairing also guarantees progress: mid is always strictly less than hi, so the range shrinks every step.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Check every index against both neighbors | O(n) | O(1) |
| First descent from the left | O(n) | O(1) |
| Binary search on the slope | O(log n) | O(1), or O(log n) if written recursively |
Edge cases
- One element: it is a peak, and the loop never runs.
- Two elements: the larger one is the peak, found after one comparison.
- Strictly increasing values: the answer is the last index. Strictly decreasing: the first.
- Negative numbers and very large numbers: only comparisons are used, so they need nothing special. The imaginary values beyond the ends are never actually read.
Mistakes to avoid
- Writing while lo <= hi with hi = mid, which can loop forever when lo equals hi.
- Comparing nums[mid] with nums[mid - 1] without checking that mid - 1 exists.
- Setting hi = mid - 1 on a falling slope, which can throw away the peak at mid.
- Claiming the search finds the highest value. It finds a local peak, not the global maximum.
- Ignoring the no-equal-neighbors rule. With flat stretches the slope test breaks down, and the worst case becomes linear.
Follow-up questions
- Neighbors may be equal. A long flat stretch gives the comparison nothing to go on, so in the worst case you must look at every element. Say that, and fall back to the scan.
- Mountain array with exactly one peak. The same code applies, and the answer is unique.
- A peak in a grid, larger than all four neighbors. Binary search on columns: find the largest value in the middle column, compare it with its left and right neighbors, and move toward the larger one. That is about O(rows · log columns).
- Return every peak. Then there is no shortcut: scan once and collect them in O(n).
Explaining it in the interview
Fictional example
- Candidate
- The array isn't sorted, but binary search only needs a way to keep an answer in one half. Here that's the slope.
- Candidate
- If the value after mid is bigger, I'm going uphill, and going uphill can't continue forever. It either drops, giving a peak, or hits the end, which also counts. So I move lo to mid plus one. Otherwise there's a peak at mid or to its left, so hi becomes mid.
- Candidate
- When lo meets hi, that index is a peak. Logarithmic time, constant space, and it relies on neighbors never being equal.
Related walkthroughs
Bit manipulation tricks explains the unsigned-shift midpoint used in the JavaScript version and when it is safe. Daily Temperatures is another problem about comparing each value with its neighbors, solved with a stack instead of halving. See the coding problems hub for more.
Practice support from Natively
Natively runs on Mac and Windows, and in practice it can read this prompt from a screenshot, and when you ask, suggest arrays where a careless boundary would loop forever, so you can test your invariant. It transcribes your mock round and saves notes, so you can review whether you justified the uphill argument or skipped it. Visit the AI interview assistant page for more.
Questions people ask
How do you find a peak element in O(log n)?
Binary search on the slope. If nums[mid] is less than nums[mid + 1], a peak exists to the right, so set lo to mid + 1; otherwise a peak exists at mid or to its left, so set hi to mid. When lo equals hi, that index is a peak.
Why does binary search work when the array is not sorted?
Binary search only needs a test that keeps an answer in one half. Going uphill must end in a drop or at the array's edge, and both mean a peak, so moving toward the higher neighbor never loses every peak.
Does Find Peak Element return the highest value?
No. It returns some local peak, an element bigger than its neighbors. When several peaks exist, any one is accepted, and different methods may return different ones.
What if neighboring values can be equal?
Then the slope test can fail on flat stretches, and in the worst case you must check every element, so the time becomes O(n).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
