[Geeks for Geeks] Peak element

Peak element

An element is called a peak element if its value is not smaller than the value of its adjacent elements(if they exists).

Given an array arr[] of size N, find the index of any one of its peak elements.

Note: The generated output will always be 1 if the index that you return is correct. Otherwise output will be 0.

  • Time : O(logn)
  • Space : O(1)
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
class Solution
{
public:
int peakElement(int arr[], int n) {
if(n == 1) return 0;
if(n == 2) {
if(arr[0] == arr[1]) return -1;
return arr[0] > arr[1] ? 0 : 1;
}
int l = 0, r = n - 1;
while(l <= r) {
int m = l + (r - l) / 2;

if(m == 0) {
if(arr[m + 1] < arr[m]) return m;
return -1;
} else if(m == n - 1) {
if(arr[m - 1] < arr[m]) return m;
return -1;
} else {
if(arr[m] > arr[m - 1] and arr[m] > arr[m + 1]) return m;
if(arr[m + 1] > arr[m - 1]) l = m + 1;
else r = m - 1;
}
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/peak-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.