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
- 1 ≤ nums.length ≤ 1000
- -2³¹ ≤ nums[i] ≤ 2³¹ − 1
- nums[i] ≠ nums[i + 1]
- Must run in O(log n)
Edge cases to test
- One element
- Strictly increasing: the last index
- Strictly decreasing: index 0
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 loC++
#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
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)