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 neighbous 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.
// A C++ program to find a peak element #include <bits/stdc++.h> using namespace std; // Find the peak element in the array int findPeak(int arr[], int n) { // first or last element is peak element if (n == 1) return arr[0]; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (int i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } } // Driver Code int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, n); return 0; } // This code is contributed by Arnab Kundu |
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, initilize 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> using namespace std; // A binary search based function // that returns index of a peak element int findPeakUtil(int arr[], int low, int high, int n) { // Find index of middle element // (low + high)/2 int mid = 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])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(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 return findPeakUtil( arr, (mid + 1), high, n); } // A wrapper over recursive function findPeakUtil() int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, n); return 0; } // This code is contributed by rathbhupendra |
C
// 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 int findPeakUtil( int arr[], int low, int high, int n) { // Find index of middle element // (low + high)/2 int mid = 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])) return mid; // If middle element is not peak and // its left neighbour is greater // than it, then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(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 return findPeakUtil(arr, (mid + 1), high, n); } // A wrapper over recursive function findPeakUtil() int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } /* Driver program to check above functions */int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf( "Index of a peak point is %d", findPeak(arr, n)); return 0; } |
Java
// A Java program to find a peak // element using divide and conquer import java.util.*; import java.lang.*; import java.io.*; class PeakElement { // A binary search based function // that returns index of a peak element static int findPeakUtil( int arr[], int low, int high, int n) { // Find index of middle element // (low + high)/2 int mid = 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])) return mid; // If middle element is not peak // and its left neighbor is // greater than it, then left half // must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak // and its right neighbor // is greater than it, then right // half must have a peak // element else return findPeakUtil( arr, (mid + 1), high, n); } // A wrapper over recursive function // findPeakUtil() static int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver method public static void main(String[] args) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.println( "Index of a peak point is " + findPeak(arr, n)); } } |
Python3
# A python 3 program to find a peak # element element using divide and conquer # A binary search based function # that returns index of a peak element def findPeakUtil(arr, low, high, n): # Find index of middle element # (low + high)/2 mid = low + (high - low)/2 mid = int(mid) # Compare middle element with its # neighbours (if neighbours exist) if ((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): return mid # If middle element is not peak and # its left neighbour is greater # than it, then left half must # have a peak element elif (mid > 0 and arr[mid - 1] > arr[mid]): return findPeakUtil(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: return findPeakUtil(arr, (mid + 1), high, n) # A wrapper over recursive # function findPeakUtil() def findPeak(arr, n): return findPeakUtil(arr, 0, n - 1, n) # Driver code arr = [1, 3, 20, 4, 1, 0] n = len(arr) print("Index of a peak point is", findPeak(arr, n)) # This code is contributed by # Smitha Dinesh Semwal |
C#
// A C# program to find // a peak element element // using divide and conquer using System; class GFG { // A binary search based // function that returns // index of a peak element static int findPeakUtil(int[] arr, int low, int high, int n) { // Find index of // middle element int mid = 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])) return mid; // If middle element is not // peak and its left neighbor // is greater than it, then // left half must have a // peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not // peak and its right neighbor // is greater than it, then // right half must have a peak // element else return findPeakUtil(arr, (mid + 1), high, n); } // A wrapper over recursive // function findPeakUtil() static int findPeak(int[] arr, int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code static public void Main() { int[] arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.WriteLine("Index of a peak " + "point is " + findPeak(arr, n)); } } // This code is contributed by ajit |
PHP
<?php // A PHP program to find a // peak element element using // divide and conquer // A binary search based function // that returns index of a peak // element function findPeakUtil($arr, $low, $high, $n) { // Find index of middle element $mid = $low + ($high - $low) / 2; // (low + high)/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])) return $mid; // If middle element is not peak // and its left neighbour is greater // than it, then left half must // have a peak element else if ($mid > 0 && $arr[$mid - 1] > $arr[$mid]) return findPeakUtil($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 return(findPeakUtil($arr, ($mid + 1), $high, $n)); } // A wrapper over recursive // function findPeakUtil() function findPeak($arr, $n) { return floor(findPeakUtil($arr, 0, $n - 1, $n)); } // Driver Code $arr = array(1, 3, 20, 4, 1, 0); $n = sizeof($arr); echo "Index of a peak point is ", findPeak($arr, $n); // This code is contributed by ajit ?> |
Output:
Index of a peak point is 2
Compelxity 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.
Exercise:
Consider the following modified definition of peak element. An array element is a peak if it is greater than its neighbours. Note that an array may not contain a peak element with this modified definition.
References:
http://courses.csail.mit.edu/6.006/spring11/lectures/lec02.pdf
http://www.youtube.com/watch?v=HtSuA80QTyo
Asked in: Amazon
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Find a peak element in a 2D array
- Find subarray of Length K with Maximum Peak
- Minimum peak elements from an array by their repeated removal at every iteration of the array
- Largest element smaller than current element on left for every element in Array
- Find the element that appears once in an array where every other element appears twice
- Find Array formed by adding each element of given array with largest element in new array to its left
- Find just strictly greater element from first array for each element in second array
- Find last element after deleting every second element in array of n integers
- Replace every element with the greatest element on right side
- Replace every element with the least greater element on its right
- Closest greater element for every array element from another array
- Range Query on array whose each element is XOR of index value and previous element
- Sum of product of each element with each element after it
- Replace every element with the greatest element on its left side
- Longest Subarray with first element greater than or equal to Last element
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element with the smallest element on its left side
- Replace each element by the difference of the total size of the array and frequency of that element
- Replace every element of the array by its previous element
- Replace every element of the array by its next element

