Given an array of integers. Find a peak element in it. An array element is a peak if it is NOT smaller than its neighbours. For corner elements, we need to consider only one neighbour.
Example:
Input: array[]= {5, 10, 20, 15}
Output: 20
The element 20 has neighbours 10 and 15,
both of them are less than 20.
Input: array[] = {10, 20, 15, 2, 23, 90, 67}
Output: 20 or 90
The element 20 has neighbours 10 and 15,
both of them are less than 20, similarly 90 has neighbours 23 and 67.
Following corner cases give better idea about the problem.
If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}.
If the input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}.
If all elements of input array are same, every element is a peak element.
It is clear from the above examples that there is always a peak element in the input array.
Naive Approach: The array can be traversed and the element whose neighbours are less than that element can be returned. Algorithm:
If in the array, the first element is greater than the second or the last element is greater than the second last, print the respective element and terminate the program.
Else traverse the array from the second index to the second last index
If for an element array[i], it is greater than both its neighbours, i.e., array[i] > array[i-1] and array[i] > array[i+1], then print that element and terminate.
C++
// A C++ program to find a peak element
#include <bits/stdc++.h>
usingnamespacestd;
// Find the peak element in the array
intfindPeak(intarr[], intn)
{
// first or last element is peak element
if(n == 1)
return0;
if(arr[0] >= arr[1])
return0;
if(arr[n - 1] >= arr[n - 2])
returnn - 1;
// check for every other element
for(inti = 1; i < n - 1; i++) {
// check if the neighbors are smaller
if(arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
returni;
}
}
// Driver Code
intmain()
{
intarr[] = { 1, 3, 20, 4, 1, 0 };
intn = sizeof(arr) / sizeof(arr[0]);
cout << "Index of a peak point is "<< findPeak(arr, n);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// A C program to find a peak element
#include <stdio.h>
// Find the peak element in the array
intfindPeak(intarr[], intn)
{
// first or last element is peak element
if(n == 1)
return0;
if(arr[0] >= arr[1])
return0;
if(arr[n - 1] >= arr[n - 2])
returnn - 1;
// check for every other element
for(inti = 1; i < n - 1; i++) {
// check if the neighbors are smaller
if(arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
returni;
}
}
// Driver Code
intmain()
{
intarr[] = { 1, 3, 20, 4, 1, 0 };
intn = sizeof(arr) / sizeof(arr[0]);
printf("Index of a peak point is %d",findPeak(arr, n));
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// A Java program to find a peak element
importjava.util.*;
classGFG {
// Find the peak element in the array
staticintfindPeak(intarr[], intn)
{
// First or last element is peak element
if(n == 1)
return0;
if(arr[0] >= arr[1])
return0;
if(arr[n - 1] >= arr[n - 2])
returnn - 1;
// Check for every other element
for(inti = 1; i < n - 1; i++) {
// Check if the neighbors are smaller
if(arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
returni;
}
return0;
}
// Driver Code
publicstaticvoidmain(String[] args)
{
intarr[] = { 1, 3, 20, 4, 1, 0};
intn = arr.length;
System.out.print("Index of a peak point is "+ findPeak(arr, n));
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python3
# A Python3 program to find a peak element
# Find the peak element in the array
deffindPeak(arr, n) :
# first or last element is peak element
if(n ==1) :
return0
if(arr[0] >=arr[1]) :
return0
if(arr[n -1] >=arr[n -2]) :
returnn -1
# check for every other element
fori inrange(1, n -1) :
# check if the neighbors are smaller
if(arr[i] >=arr[i -1] andarr[i] >=arr[i +1]) :
returni
# Driver code.
arr =[ 1, 3, 20, 4, 1, 0]
n =len(arr)
print("Index of a peak point is", findPeak(arr, n))
document.write("Index of a peak point is "+ findPeak(arr, n));
// This code is contributed by rdtank.
</script>
Output:
Index of a peak point is 2
Complexity Analysis:
Time complexity: O(n). One traversal is needed so the time complexity is O(n)
Space Complexity: O(1). No extra space is needed, so space complexity is constant
Efficient Approach:Divide and Conquer can be used to find a peak in O(Logn) time. The idea is based on the technique of Binary Search to check if the middle element is the peak element or not. If the middle element is not the peak element, then check if the element on the right side is greater than the middle element then there is always a peak element on the right side. If the element on the left side is greater than the middle element then there is always a peak element on the left side. Form a recursion and the peak element can be found in log n time.
Algorithm:
Create two variables, l and r, initialize l = 0 and r = n-1
Iterate the steps below till l <= r, lowerbound is less than the upperbound
Check if the mid value or index mid = (l+r)/2, is the peak element or not, if yes then print the element and terminate.
Else if the element on the left side of the middle element is greater then check for peak element on the left side, i.e. update r = mid – 1
Else if the element on the right side of the middle element is greater then check for peak element on the right side, i.e. update l = mid + 1
C++
// A C++ program to find a peak element
// using divide and conquer
#include <bits/stdc++.h>
usingnamespacestd;
// A binary search based function
// that returns index of a peak element
intfindPeakUtil(intarr[], intlow,
inthigh, intn)
{
// Find index of middle element
// (low + high)/2
intmid = low + (high - low) / 2;
// Compare middle element with its
// neighbours (if neighbours exist)
if((mid == 0 || arr[mid - 1] <= arr[mid]) &&
(mid == n - 1 || arr[mid + 1] <= arr[mid]))
returnmid;
// If middle element is not peak and its
// left neighbour is greater than it,
// then left half must have a peak element
elseif(mid > 0 && arr[mid - 1] > arr[mid])
returnfindPeakUtil(arr, low, (mid - 1), n);
// If middle element is not peak and its
// right neighbour is greater than it,
// then right half must have a peak element
else
returnfindPeakUtil(
arr, (mid + 1), high, n);
}
// A wrapper over recursive function findPeakUtil()
// A wrapper over recursive function findPeakUtil()
functionfindPeak(arr, n)
{
returnfindPeakUtil(arr, 0, n - 1, n);
}
// Driver Code
vararr = [ 1, 3, 20, 4, 1, 0 ];
varn = arr.length;
document.write("Index of a peak point is "
+ findPeak(arr, n));
</script>
Output:
Index of a peak point is 2
Complexity Analysis:
Time Complexity: O(Logn). Where n is the number of elements in the input array. In each step our search becomes half. So it can be compared to Binary search, So the time complexity is O(log n)
Space complexity: O(1). No extra space is required, so the space complexity is constant.
Iterative Approach :The below given code is the iterative version of the above explained and demonstrated recursive based divide and conquer technique.
C++
// A C++ program to find a peak element
// using divide and conquer
#include <bits/stdc++.h>
usingnamespacestd;
// A binary search based function
// that returns index of a peak element
intfindPeakUtil(intarr[], intlow, inthigh, intn)
{
intl = low;
intr = high;
intmid;
while(l <= r) {
// finding mid by binary right shifting.
mid = (l + r) >> 1;
// first case if mid is the answer
if((mid == 0 || arr[mid - 1] <= arr[mid])
and (mid == n - 1 || arr[mid + 1] <= arr[mid]))
break;
// if we have to perform left recursion
if(mid > 0 and arr[mid - 1] > arr[mid])
r = mid - 1;
// else right recursion.
else
l = mid + 1;
}
returnmid;
}
// A wrapper over recursive function findPeakUtil()
intfindPeak(intarr[], intn)
{
returnfindPeakUtil(arr, 0, n - 1, n);
}
// Driver Code
intmain()
{
intarr[] = { 1, 3, 20, 4, 1, 0 };
intn = sizeof(arr) / sizeof(arr[0]);
cout << "Index of a peak point is "<< findPeak(arr, n);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// A C program to find a peak element using divide and
// conquer
#include <stdio.h>
// A binary search based function
// that returns index of a peak element
intfindPeakUtil(intarr[], intlow, inthigh, intn)
{
intl = low;
intr = high;
intmid;
while(l <= r) {
// finding mid by binary right shifting.
mid = (l + r) >> 1;
// first case if mid is the answer
if((mid == 0 || arr[mid - 1] <= arr[mid])
&& (mid == n - 1 || arr[mid + 1] <= arr[mid]))
break;
// if we have to perform left recursion
if(mid > 0 && arr[mid - 1] > arr[mid])
r = mid - 1;
// else right recursion.
else
l = mid + 1;
}
returnmid;
}
// A wrapper over recursive function findPeakUtil()
intfindPeak(intarr[], intn)
{
returnfindPeakUtil(arr, 0, n - 1, n);
}
// Driver Code
intmain()
{
intarr[] = { 1, 3, 20, 4, 1, 0 };
intn = sizeof(arr) / sizeof(arr[0]);
printf("Index of a peak point is %d", findPeak(arr, n));
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// A Java program to find a peak element using divide and
// conquer
classGFG {
// A binary search based function that returns index of
// A wrapper over recursive function findPeakUtil()
staticintfindPeak(int[]arr, intn) {
returnfindPeakUtil(arr, 0, n - 1, n);
}
// Driver Code
publicstaticvoidMain(String []args) {
int[]arr = { 1, 3, 20, 4, 1, 0 };
intn = arr.Length;
Console.WriteLine("Index of a peak point is "+ findPeak(arr, n));
}
}
// This code is contributed by shikhasingrajput
Javascript
<script>
// A JavaScript program to find a peak element
// using divide and conquer
// A binary search based function
// that returns index of a peak element
functionfindPeakUtil(arr,low,high,n)
{
let l = low;
let r = high;
let mid;
while(l<=r)
{
// finding mid by binary right shifting.
mid = (l + r)>>1;
// first case if mid is the answer
if((mid == 0 || arr[mid - 1] <= arr[mid]) &&
(mid == n - 1 || arr[mid + 1] <= arr[mid]))
break;
// if we have to perform left recursion
if(mid > 0 && arr[mid - 1] > arr[mid])
r = mid - 1;
// else right recursion.
elsel = mid + 1;
}
returnmid;
}
// A wrapper over recursive function findPeakUtil()
functionfindPeak(arr,n)
{
returnfindPeakUtil(arr, 0, n - 1, n);
}
// Driver Code
let arr = [ 1, 3, 20, 4, 1, 0 ];
let n = arr.length;
document.write("Index of a peak point is "+findPeak(arr, n));
// This code is contributed by shinjanpatra
</script>
Output
Index of a peak point is 2
Exercise: Consider the following modified definition of peak element. An array element is a peak if it is greater than its neighbors. Note that an array may not contain a peak element with this modified definition.
Related Problem: Find local minima in an array Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy