Cover image for Interview Classic 150 Questions P162 Find Peak Element

Interview Classic 150 Questions P162 Find Peak Element


Timeline

timeline

2025-12-03

init

divide and conquer

Title:

  • If nums[mid] < nums[mid + 1] ⇒ peak must be in the right half
    Because from left to right it is increasing, and the rightmost is -∞, the right half must have a peak (even if monotonically increasing, the last one is a peak).
  • If nums[mid] > nums[mid + 1] ⇒ peak must be in the left half
    Because from right to left it is increasing, and the leftmost is -∞, the left half must have a peak.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <vector>
using std::vector;

class Solution {
private:
bool isPeak(vector<int> &nums, int mid)
{
int n = nums.size();
if (mid != 0 && nums[mid] <= nums[mid - 1]) {
return false;
}
if (mid != n - 1 && nums[mid] <= nums[mid + 1]) {
return false;
}
return true;
}

public:
int findPeakElement(vector<int> &nums)
{
int n = nums.size();
int left = 0, right = n - 1, mid;

while (left <= right) {
mid = left + (right - left) / 2;
if (isPeak(nums, mid)) {
return mid;
}

if (nums[mid] < nums[mid + 1]) {
// If nums[mid] < nums[mid + 1] ⇒ peak must be in the right half
// Because from left to right it is increasing, and the rightmost is -∞, the right half must have a peak.

left = mid + 1;
} else {
// If nums[mid] > nums[mid + 1] ⇒ peak must be in the left half
// Since it is increasing from right to left, and the leftmost is -∞, the left half must have a peak.

right = mid - 1;
}
}

return mid;
}
};