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 in which no two neighbouring numbers are equal, return the index of any peak.

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
Input: nums = [1, 2, 3, 1]
Output: 2
Explanation: 3, at index 2, is bigger than both 2 and 1.
Example 2
Input: nums = [1, 2, 1, 3, 5, 6, 4]
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.
Solution

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], is such a ridge: each number is the height at one position, and index 1 (height 2) and index 5 (height 6) are peaks.

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 = 3, and its height is 3. The next number, at index 4, is 5. So the ground rises to the right, marked uphill: 3 < 5.

The array 1, 2, 1, 3, 5, 6, 4 drawn as bars. At mid = 3 the value 3 is less than the next value 5, so the slope goes uphill. Indexes 0 to 3 are dropped and lo = 4 to hi = 6 is kept; it holds the peak 6 at index 5. Index 1 is also a peak.

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: lo, the first, and hi, the last. At the start they cover the whole array, which always holds a peak. Its largest number is always a peak, since no neighbour can equal it.

The rule that no two neighbours are equal matters. In [2, 2, 2] no number is strictly bigger than its neighbours, so there is no peak, and the slope points nowhere.

Following the slope

How does the middle shrink the range? Take mid, the middle index between lo and hi, rounded down. Writing it as lo + (hi - lo) / 2 rather than (lo + hi) / 2 never adds lo and hi, a sum that could pass the largest int value on a very large array.

If nums[mid] < nums[mid + 1], the ground goes uphill. mid is not a peak, since its right neighbour is bigger, and a peak lies to its right, so lo moves to mid + 1. Otherwise the ground goes downhill, and mid itself may be the peak, so hi moves to mid and keeps it in the range.

When to stop

When is the search over? It runs while lo < hi. Once the two meet, one index is left, and since the range always holds a peak, that index is one. While lo < hi, the rounded-down mid is always below hi, so mid + 1 is still inside the array.

Java Solution

The method findPeakElement works in these steps:

  1. First, set lo to 0 and hi to the last index, nums.length - 1, so the range covers the whole array.
  2. Loop while lo < hi. Inside, find the middle index mid with lo + (hi - lo) / 2.
  3. Compare nums[mid] with nums[mid + 1]. If it is smaller, the slope goes uphill, so set lo = mid + 1. Otherwise it goes downhill, so set hi = mid.
  4. When the loop ends, lo and hi are the same index, a peak, so return lo.

The main method runs both examples, a single number, an array that only rises, one that only falls, and [3, 1, 2], which has a peak at each end. A small helper, show, prints each array with the index found and the value there.

Java
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:

Output
[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. For [7], lo and hi both start at 0, so the loop never runs and index 0 comes back.

[1, 2, 3, 4] only rises and gives its last index, 3, while [4, 3, 2, 1] only falls and gives index 0. Both are peaks only because the outside counts as lower than every number. In the last line, [3, 1, 2] has a peak at each end. mid is index 1, its 1 is smaller than the 2 after it, so the search goes right and returns index 2.

Why lo < hi and not lo <= hi? With lo <= hi and the same updates, the loop goes on after the two meet: mid equals hi, and hi = mid changes nothing. A test of that version on [1, 2, 3, 1] was still looping after 1,000 passes. On [1, 2] it read nums[2] and threw an 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 lo to hi that holds a peak, so about log2 n passes leave one index. For a million numbers, that is about 20 passes.
  • Space: O(1), because the search keeps only the three indexes lo, hi and mid, and never copies or changes nums.