The 30 second answer
A peak is an element strictly greater than its neighbours, and the official problem treats the positions just outside the array as negative infinity, so a peak always exists. I look at mid and mid + 1: if mid is less than mid + 1, a peak lies to the right, otherwise mid itself may be a peak and I search to the left. Any peak is accepted.
Problem A peak element is strictly greater than its neighbours. Given an array, return the index of any peak. The problem asks for O(log n) time, and it treats the positions just outside the array as negative infinity, so a peak always exists. Neighbour values are guaranteed not to be equal. Original: LeetCode 162: Find Peak Element.
Understanding the prompt You may return any peak, not the global maximum, although a global maximum is always a peak under these rules. Equal neighbours are excluded, so mid and mid + 1 always tell you a direction. The imaginary bounds at the ends make a single-element array a peak.
Pattern recognition Boundary binary search on a unimodal step: move toward the larger neighbour, which is a direction that must contain a peak.
Brute force A linear scan that returns the first i where nums[i] > nums[i+1], or the last index: O(n).
Optimal 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. The loop ends on a peak index. Because hi starts at n - 1 and lo < hi, mid + 1 is always in range.
Alternatives A linear scan is correct but not what the logarithmic brief asks for.
Java solution
public class FindPeakElement {
static 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;
else hi = mid;
}
return lo;
}
public static void main(String[] args) {
System.out.println(findPeakElement(new int[] {1, 2, 3, 1})); // 2
System.out.println(findPeakElement(new int[] {1, 2, 1, 3, 5, 6, 4})); // 5
System.out.println(findPeakElement(new int[] {1})); // 0
}
}Complexity O(log n) time, O(1) extra space.
Edge cases
- Official samples: [1,2,3,1] returns 2; [1,2,1,3,5,6,4] may return 5 (the 6) or 1 (the first 2); the solution below returns 5.
- A single element returns 0.
- A strictly decreasing array peaks at index 0; a strictly increasing one peaks at the last index.
Follow-ups
- Find Peak Element II is the 2D version, still logarithmic in one dimension per step.
- If equals were allowed, you would need a different argument.
Tests [1,2,3,1] returns 2. [1,2,1,3,5,6,4] returns 5. 1 returns 0.
How to say it in the interview "A peak always exists because the ends are treated as negative infinity. I compare mid with mid + 1 and move toward the larger one, keeping mid in the range when it is already larger. The search lands on a peak in logarithmic time."
Sources (1)
- LeetCode 162: Find Peak Elementleetcode.com