Algo-Sim › Binary Search

Find Peak Element

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Return the index of any element greater than its neighbours, in O(log n), by following the uphill slope.

Problem

A peak is an element strictly greater than its neighbours, and positions just outside the array count as −∞. Given nums where no two neighbours are equal, return the index of any peak, in O(log n) time.

Constraints

Edge cases to test

Follow-up questions

Why does following the slope always find a peak?
The ends act as −∞, so the uphill side must eventually turn down. Each step keeps a half that contains a peak.
What about a 2D grid?
Binary search on columns: find the max in the middle column and move toward a bigger neighbour: O(m log n) (LC 1901).

Solution

Java

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]) {
            hi = mid;
        } else {
            lo = mid + 1;
        }
    }
    return lo;
}

Python

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int findPeakElement(vector<int> &nums) {
        int lo = 0, hi = int(nums.size()) - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] > nums[mid + 1]) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        return lo;
    }
};

More Binary Search problems