Find Peak Element

Pattern: Binary search on sorted arrays

medium

The array is not sorted, but comparing nums[mid] with nums[mid + 1] still tells you which side must hold a peak. Walk uphill, and you always reach one.

The problem

A peak is a value strictly bigger than its neighbours. Values outside the array count as minus infinity, so the ends can be peaks too. Neighbouring values are never equal. Return the index of any peak, in O(log n) time. For example, [1, 2, 3, 1] gives 2, and [1, 2, 1, 3, 5, 6, 4] gives 1 or 5.

The function name findPeakElement matches LeetCode. Use the link above for the exact statement and limits. Since any peak is correct, this guide's tests check that the returned index is a peak, not that it is one exact index.

Think first

  • If nums[mid] < nums[mid + 1], walk right from mid + 1. Must you meet a peak? Why?
  • If nums[mid] > nums[mid + 1], which side surely has a peak?
  • The array is not sorted. What makes binary search still work?

Hints

    Brute force, and why it fails

    Check every index against its neighbours, or return the index of the largest value: O(n). The rule asks for O(log n).

    The key insight

    Binary search does not need a sorted array, only a test that rules out one side. "The slope at mid goes up to the right" guarantees a peak on the right, so half can be thrown away each time.

    Dry run

    10lo
    21 
    12 
    33 
    54 
    65 
    46hi

    nums = [1, 2, 1, 3, 5, 6, 4]. Peaks are at index 1 (2) and index 5 (6). Either is a correct answer.

    Step 1 of 4

    The plan

    lo = 0, hi = n - 1
    while lo < hi:
        mid = lo + (hi - lo) / 2
        if nums[mid] < nums[mid + 1]: lo = mid + 1
        else: hi = mid
    return lo
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    The range holding a sure peak halves each step.

    Edge cases

    • One value: index 0 is a peak.
    • Strictly rising: the last index. Strictly falling: index 0.
    • mid + 1 is always inside the range, because mid < hi while lo < hi.
    I've built my logic, show the code

    Java

    class Solution {
        public int findPeakElement(int[] nums) {
            int lo = 0, hi = nums.length - 1;
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] < nums[mid + 1]) lo = mid + 1;   // going uphill: a peak lies to the right
                else hi = mid;                                 // going downhill: mid or something left is a peak
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        int findPeakElement(vector<int>& nums) {
            int lo = 0, hi = static_cast<int>(nums.size()) - 1;
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] < nums[mid + 1]) lo = mid + 1;   // going uphill: a peak lies to the right
                else hi = mid;                                 // going downhill: mid or something left is a peak
            }
            return lo;
        }
    };

    Python

    class Solution:
        def findPeakElement(self, nums: list[int]) -> int:
            lo, hi = 0, len(nums) - 1
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] < nums[mid + 1]:
                    lo = mid + 1                    # going uphill: a peak lies to the right
                else:
                    hi = mid                        # going downhill: mid or something left is a peak
            return lo

    Common mistakes

    • Comparing with nums[mid - 1] without checking that it exists.
    • Setting hi = mid - 1 on a downhill slope, which can throw away the peak at mid.
    • Thinking the answer must be the highest value. Any peak counts.

    Similar problems