Find Peak Element
Find a number bigger than both of its neighbours in O(log n) steps, by following the slope with binary search.
In an array, a peak is a number that is strictly bigger than the numbers right next to it. Given an array of integers nums
The first and last numbers have only one neighbour inside the array. Treat the places just outside the array as smaller than every number, so the first or last number only has to beat its one real neighbour. The solution must take O(log n) steps, where n is the length of nums
Example 1
Output: 2
Explanation: 3, at index 2, is bigger than both 2 and 1.
Example 2
Output: 5
Explanation: 6, at index 5, is a peak. Index 1, the 2, is also a peak, so 1 is a correct answer too.
The Idea
Picture walking along a mountain ridge in thick fog. You can only see the ground right next to your feet. A peak is a spot higher than the ground on both sides of it. The array of Example 2, [1, 2, 1, 3, 5, 6, 4]
The simple way to find one is to look at every number in turn and stop at the first one bigger than both neighbours. That can take n looks. The problem asks for O(log n): about as many looks as the times n can be halved before reaching 1. For a million numbers, that is about 20 looks instead of a million.
Halving like that is what binary search does: look at the middle of a range, throw away the half that cannot hold the answer, and repeat on the other half. It usually runs on sorted arrays, where the middle value tells you which half to keep. This array is not sorted. So what can one look at the middle tell us?
Look at the picture below. The middle index of the array is 3, marked mid = 3uphill: 3 < 5
Keep walking right from index 3 and one of two things happens. Either the ground goes down somewhere, and the last spot before it goes down is a peak. Or the ground keeps rising to the end of the array, and the last number is a peak, because the outside, drawn as −∞ at both ends of the picture, counts as lower than everything.
Either way, a peak lies to the right of index 3. That is why the picture marks indexes 0 to 3 as dropped and keeps 4 to 6, even though index 1 is also a peak: one peak is all we need. In the kept part, the peak is the 6 at index 5.
Had the ground gone down to the right of the middle, the same walk, now to the left, would end at a peak at the middle or left of it. So one comparison, of the middle number with the next one, always points to a half that still holds a peak. Binary search works here on the slope, not on sorted values.
Solution Approach
Turning that idea into code means settling three things: how to mark the part that still holds a peak, how to shrink it on each slope, and when to stop.
The range that holds a peak
Which positions are still in play? Two indexes mark them: lohi
The rule that no two neighbours are equal matters. In [2, 2, 2]
Following the slope
How does the middle shrink the range? Take midlohilo + (hi - lo) / 2(lo + hi) / 2lohiint
If nums[mid] < nums[mid + 1]midlomid + 1midhimid
When to stop
When is the search over? It runs while lo < hilo < himidhimid + 1
Java Solution
The method findPeakElement
- First, set
to 0 andlo to the last index,hi , so the range covers the whole array.nums.length - 1 - Loop while
. Inside, find the middle indexlo < hi withmid .lo + (hi - lo) / 2 - Compare
withnums[mid] . If it is smaller, the slope goes uphill, so setnums[mid + 1] . Otherwise it goes downhill, so setlo = mid + 1 .hi = mid - When the loop ends,
andlo are the same index, a peak, so returnhi .lo
The main[3, 1, 2]show
import java.util.Arrays;
public class FindPeakElement {
public static int findPeakElement(int[] nums) {
int lo = 0;
int hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < nums[mid + 1]) {
lo = mid + 1; // uphill to the right: a peak lies right of mid
} else {
hi = mid; // downhill to the right: a peak at mid or left of it
}
}
return lo; // lo == hi: the one index left is a peak
}
static void show(int[] nums) {
int peak = findPeakElement(nums);
System.out.println(Arrays.toString(nums) + " -> index " + peak
+ " (value " + nums[peak] + ")");
}
public static void main(String[] args) {
show(new int[] {1, 2, 3, 1});
show(new int[] {1, 2, 1, 3, 5, 6, 4});
show(new int[] {7});
show(new int[] {1, 2, 3, 4});
show(new int[] {4, 3, 2, 1});
show(new int[] {3, 1, 2});
}
}
Running it prints:
[1, 2, 3, 1] -> index 2 (value 3)
[1, 2, 1, 3, 5, 6, 4] -> index 5 (value 6)
[7] -> index 0 (value 7)
[1, 2, 3, 4] -> index 3 (value 4)
[4, 3, 2, 1] -> index 0 (value 4)
[3, 1, 2] -> index 2 (value 2)
Look at the second line: index 5, value 6, the peak the picture leads to. Index 1 is a peak too, but the search dropped it in its first step, when it went uphill from mid = 3[7]lohi
[1, 2, 3, 4][4, 3, 2, 1][3, 1, 2]mid
Why lo < hilo <= hilo <= himidhihi = mid[1, 2, 3, 1][1, 2]nums[2]ArrayIndexOutOfBoundsException
Complexity
Each pass of the loop makes one comparison and keeps about half of the range.
- Time: O(log n), because each pass keeps only the half of
tolo that holds a peak, so about log2 n passes leave one index. For a million numbers, that is about 20 passes.hi - Space: O(1), because the search keeps only the three indexes
,lo andhi , and never copies or changesmid .nums