Skip to main content

Peak Element

Problem​

Given an 0-indexed array of integers arr[] of size n, find its peak element and return it's index. An element is considered to be peak if it's value is greater than or equal to the values of its adjacent elements (if they exist).

Note: The output will be 1 if the index returned by your function is correct; otherwise, it will be 0.

Examples:​

Example 1:

Input: n = 3, arr[] = {1, 2, 3} 
Output: 1
Explanation: If the index returned is 2, then the output printed will be 1. Since arr[2] = 3 is greater than its adjacent elements, and there is no element after it, we can consider it as a peak element. No other index satisfies the same property, so answer will be printed as 0.

Example 2:

Input: n = 7, arr[] = {1, 1, 1, 2, 1, 1, 1}
Output: 1
Explanation: In this case there are 5 peak elements with indices as {0,1,3,5,6}. Returning any of them will give you correct answer.

Solution​

Python

def peakElement(self,arr, n):
if (n == 1) :
return 0
if (arr[0] >= arr[1]) :
return 0
if (arr[n - 1] >= arr[n - 2]) :
return n - 1
for i in range(1, n - 1) :
if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]) :
return i

Java

public int peakElement(int[] arr,int n) {
if (n == 1)
return 0;
if (arr[0] >= arr[1])
return 0;
if (arr[n - 1] >= arr[n - 2])
return n - 1;
for (int i = 1; i < n - 1; i++) {
if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
return i;
}
return 0;
}

C++

public:
int peakElement(int arr[], int n) {
if (n == 1)
return 0;
if (arr[0] >= arr[1])
return 0;
if (arr[n - 1] >= arr[n - 2])
return n - 1;
for (int i = 1; i < n - 1; i++) {
if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
return i;
}
}

C

int peakElement(int arr[], int n) {
if (n == 1)
return 0;
if (arr[0] >= arr[1])
return 0;
if (arr[n - 1] >= arr[n - 2])
return n - 1;
for (int i = 1; i < n - 1; i++) {
if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
return i;
}
}
  • Time complexity: O(n)O(n)
  • Space complexity:: O(1)O(1)