Find the peak element in an array in JavaScript
Advanced · 3 min read
Picture a hike: the path climbs to one summit, then goes down the other side. A list of numbers can have the same shape, like [1, 3, 7, 12, 9, 4]. It rises to one highest value, the peak, and then falls. Daily sales over a promotion, a ball's height over time, and the temperature through a day often look like this.
In this tutorial you will find the peak's position without looking at every number. You will use a twist on binary search that compares each middle value with its right-hand neighbor. You should know how binary search halves a range. The twist is explained step by step.
The easy way first
The straightforward answer finds the largest value, then its position:
const linearPeak = (values) => values.indexOf(Math.max(...values));
console.log(linearPeak([1, 3, 7, 12, 9, 4])); // 3
It works, but it looks at every number, twice (once for Math.max, once for indexOf). For a long list we can do much better by using the shape.
What one comparison tells you
Stand anywhere on the hike and look one step ahead:
- If the next step goes up, you are still climbing. The summit is ahead of you, to the right.
- If the next step goes down, you are at the summit or past it. The summit is where you stand or behind you, to the left.
In code: if values[mid] < values[mid + 1], the peak is to the right of mid. Otherwise it is at mid or to its left. One comparison throws away half the list, just like binary search.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
5 Find the peak of a list that rises then falls
hardA list rises to a single highest value and then falls. Find that peak without checking every element.
Stuck? Three hints, smallest first
- 1. Compare the midpoint with its right-hand neighbour to decide which half holds the peak.
- 2. If
list[mid] < list[mid + 1]the peak is to the right, otherwise it is atmidor to the left. - 3. Use
while (low < high)and never look atmid + 1out of range.
Step 1: walk through one example
low=0 high=5 mid=2 7 < 12 climbing, low = 3
low=3 high=5 mid=4 9 < 4? no, high = 4
low=3 high=4 mid=3 12 < 9? no, high = 3
low=3 high=3 stop: the peak is at index 3
The range keeps shrinking until low and high meet. Where they meet is the peak.
Step 2: write the loop
low moves to mid + 1 when climbing, because mid itself can't be the peak (something bigger is right after it). high moves to mid otherwise, not mid - 1, because mid might be the peak:
function findPeak(values) {
if (values.length === 0) return -1;
let low = 0;
let high = values.length - 1;
while (low < high) {
const mid = low + Math.floor((high - low) / 2);
if (values[mid] < values[mid + 1]) low = mid + 1;
else high = mid;
}
return low;
}
console.log(findPeak([1, 3, 7, 12, 9, 4])); // 3
console.log(findPeak([1, 2, 3, 4])); // 3: only rises, peak is last
console.log(findPeak([9, 5, 2])); // 0: only falls, peak is first
console.log(findPeak([42])); // 0
console.log(findPeak([])); // -1
A list that only rises has its peak at the end, and one that only falls has it at the start. Both are handled without special cases.
Step 3: why the loop uses <
The code reads values[mid + 1]. On the last item, mid + 1 would be past the end of the list. Is that a risk?
With while (low < high), the range always has at least two items inside the loop. mid is rounded down, so it is always less than high, and mid + 1 is at most high, which is a real index. The < is what keeps the neighbor in range.
Here is the wrong turn, using <= from plain binary search:
function wrong(values) {
let low = 0;
let high = values.length - 1;
let steps = 0;
while (low <= high && steps < 10) {
steps++;
const mid = low + Math.floor((high - low) / 2);
if (values[mid] < values[mid + 1]) low = mid + 1;
else high = mid;
}
return steps;
}
console.log(wrong([1, 3, 7, 12, 9, 4])); // 10: it only stopped because of the limit
Once low equals high, high = mid changes nothing, so the loop would spin forever. The steps < 10 limit is only there so this example ends.
Step 4: check against the easy way
The two versions reason in completely different ways. If they agree on a set of test lists, you can trust the fast one:
function findPeak(values) {
if (values.length === 0) return -1;
let low = 0;
let high = values.length - 1;
while (low < high) {
const mid = low + Math.floor((high - low) / 2);
if (values[mid] < values[mid + 1]) low = mid + 1;
else high = mid;
}
return low;
}
const linearPeak = (values) => values.indexOf(Math.max(...values));
const cases = [[1, 3, 7, 12, 9, 4], [1, 2, 3, 4], [9, 5, 2], [42]];
console.log(cases.every((c) => findPeak(c) === linearPeak(c))); // true
Checking a clever solution against a simple, obviously correct one is a habit worth keeping.
The full solution
The panel runs findPeak on four lists: a peak in the middle, rising only, falling only, and one item. Press Run. The checks also cover two-item lists and an empty one.
function findPeak(values) {
if (values.length === 0) return -1;
let low = 0;
let high = values.length - 1;
// low < high, so mid + 1 is always in range.
while (low < high) {
const mid = low + Math.floor((high - low) / 2);
if (values[mid] < values[mid + 1]) low = mid + 1; // still climbing
else high = mid; // at or past the peak
}
return low;
}
const linearPeak = (values) => values.indexOf(Math.max(...values));
const cases = [
[1, 3, 7, 12, 9, 4],
[1, 2, 3, 4], // rises the whole way: peak is last
[9, 5, 2], // falls the whole way: peak is first
[42],
];
for (const c of cases) {
console.log(JSON.stringify(c).padEnd(20), 'peak at', findPeak(c), '=', c[findPeak(c)]);
}
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a peak in the middle', findPeak([1, 3, 7, 12, 9, 4]), 3);
test('a list that only rises peaks at the end', findPeak([1, 2, 3, 4]), 3);
test('a list that only falls peaks at the start', findPeak([9, 5, 2]), 0);
test('a single element', findPeak([42]), 0);
test('two rising', findPeak([1, 2]), 1);
test('two falling', findPeak([2, 1]), 0);
test('an empty list', findPeak([]), -1);
test('it agrees with the linear scan on every case', cases.every((c) => findPeak(c) === linearPeak(c)), true);
while (low < high) rather than <= is what makes values[mid + 1] safe: while the range holds two or more elements, mid is always below high, so mid + 1 exists. Cross-checking against a plain linear scan of Math.max is the cheap way to be confident, since the two use completely different reasoning to reach the same answer.
Common mistakes
- Using
while (low <= high). Withhigh = mid, the loop can never finish once the two meet. - Writing
high = mid - 1. Ifmidis the peak, that throws it away. - Using this on a list with several hills. It finds a peak, a value bigger than its neighbors, but not necessarily the highest one. It only finds the top when the list rises once and falls once.
Try it yourself
- Return the peak value instead of its index.
- Find the lowest point of a list that falls and then rises, like
[9, 4, 1, 3, 8]. (Hint: flip one comparison.) - Count how many times the loop runs for a list of 1,000 numbers that rises the whole way.