Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Find Peak Element

Easy
0/40
Average time to solve is 15m
profile
Contributed by
198 upvotes
Asked in companies
GoogleAmazonOla

Problem statement

You are given an array 'arr' of length 'n'. Find the index(0-based) of a peak element in the array. If there are multiple peak numbers, return the index of any peak number.


Peak element is defined as that element that is greater than both of its neighbors. If 'arr[i]' is the peak element, 'arr[i - 1]' < 'arr[i]' and 'arr[i + 1]' < 'arr[i]'.


Assume 'arr[-1]' and 'arr[n]' as negative infinity.


Note:
1.  There are no 2 adjacent elements having same value (as mentioned in the constraints).
2.  Do not print anything, just return the index of the peak element (0 - indexed).
3. 'True'/'False' will be printed depending on whether your answer is correct or not.


Example:

Input: 'arr' = [1, 8, 1, 5, 3]

Output: 3

Explanation: There are two possible answers. Both 8 and 5 are peak elements, so the correct answers are their positions, 1 and 3.


Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line contains an integer ‘n’, the number of elements in 'arr'.
The second line contains ‘n’ space-separated integers , the array 'arr'.


Output Format
The output contains True/ False depending whether the found number is peak element or not.


Sample Input 1:
5
1 8 1 5 3


Expected Answer:
1


Output on Console:
True


Explanation of sample input 1 :
There are two possible answers. Both 8 and 5 are peak elements, so the correct answers are their positions, 1 and 3. Any of these 2 numbers will print 'True'.


Sample Input 2:
3
1 2 1 


Expected Answer:
1


Output on Console:
True


Expected time complexity:
The expected time complexity is O(log 'n').


Constraints:
1 <= 'n' <= 10^5
1 <= 'arr[i]' <= 10^5
'arr[i]' != 'arr[i + 1]' for all 'i' in range 0 <= 'i' < 'n' - 1


Hint

Check for all elements if they are peak or not.

Approaches (2)
Brute force approach
  • The key idea is to check if each element is a peak or not.
  • To do that we first check if one of the first or last element is peak.
  • For that, we simply check if the array is sorted in increasing or decreasing order.
  • Otherwise, we take a loop from index = 1 and for each element, compare it to its left and right element to see if it is greater than both of them.
  • If it is, we have found the peak element and we return it. Otherwise, we check the next element in the array.

Keeping the above example in mind, we can write the following solution:

  • We first start with checking if the array is sorted or not. If it is sorted in decreasing order, we return the element at the 0th index as the peak element.
  • Otherwise, if sorted in increasing order, we return the last element as the peak element.
  • Otherwise, we iterate through the array using a loop and with variable ‘i’ as the iterator and check if the i-th index is peak or not by comparing it with the previous and next element of the array.
  • Once we find the peak element we return it.
Time Complexity

O(‘n’), where ‘n’ is the number of elements in the sequence.

We need to traverse the array once to find the peak element.

Hence the time complexity is O(‘N’).

Space Complexity

O(1)

We are using constant space.

Hence the space complexity is O(1).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Find Peak Element
All tags
Sort by
Search icon

Interview problems

Easy Java Solution

import java.util.ArrayList;

public class Solution {

    public static int findPeakElement(ArrayList<Integer> arr) {

        // Write your code here.

        if(arr.get(0)>arr.get(1)) return 0;

        for(int i=1;i<arr.size()-1;i++){

            if(arr.get(i)>arr.get(i-1) && arr.get(i)>arr.get(i+1)) return i;

        }

        if(arr.get(arr.size()-1)>arr.get(arr.size()-2)) return arr.size()-1;

        return 0;

    }

};

 

13 views
0 replies
0 upvotes

Interview problems

find Peak element time complexity O(log n)

int findPeakElement(vector<int> &arr) {

    int n = arr.size();

    if(n == 1) return 0;

    if(arr[0] > arr[1]) return 0; // If the peak is first element 

    if(arr[n - 1] > arr[n - 2]) return n - 1; //  If the peak is last element

    int st = 1;

    long long end = n - 2;

    while(st <= end) {

        int mid = st+(end-st)/2;

        // If the mid element is a peak element

        if(arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {

            return mid;

        }

        // If the mid is in left half it means peak is in right half

        if(arr[mid] > arr[mid - 1]) {

            st = mid + 1;

        }

        // If the mid is in right half it means peak is in left half

        else {

            end = mid - 1;

        }

    }

    return -1;

}

30 views
0 replies
0 upvotes

Interview problems

Using Binary Search C++

int findPeakElement(vector<int> &arr) {

 

    int n = arr.size();

 

    if(n == 1) return 0;

 

    if(arr[0] > arr[1]) return 0; // If the peak is first element 

 

    if(arr[n - 1] > arr[n - 2]) return n - 1; //  If the peak is last element

 

 

 

    int low = 1;

 

    long long high = n - 2;

 

    while(low <= high) {

 

        int mid = (low + high) / 2;

 

        // If the mid element is a peak element

 

        if(arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {

 

            return mid;

 

        }

 

        // If the mid is in left half it means peak is in right half

 

        if(arr[mid] > arr[mid - 1]) {

 

            low = mid + 1;

 

        }

 

        // If the mid is in right half it means peak is in left half

 

        else {

 

            high = mid - 1;

 

        }

 

    }

 

    return -1;

 

}

45 views
0 replies
0 upvotes

Interview problems

JAVA

import java.util.ArrayList;
public class Solution {
    public static int isPeak(ArrayList<Integer> arr,int low,int high){
        if (low == high) {
            return low;
        }
        int mid = low + (high - low) / 2;

        if (arr.get(mid) > arr.get(mid + 1)) {
            return isPeak(arr, low, mid);  
        } else {
            return isPeak(arr, mid + 1, high);  
        }
    }
    public static int findPeakElement(ArrayList<Integer> arr) {
        // Write your code here.
        return isPeak( arr,0, arr.size()-1);
    }
};

java

programming

40 views
0 replies
0 upvotes

Interview problems

c++

int findPeakElement(vector<int> &arr) {

    // Write your code here

    for(int i=1;i<arr.size();i++){

        if((arr[i-1]<arr[i]) && (arr[i+1]<arr[i])){

            return i;

        }

    }

}

61 views
0 replies
1 upvote

Interview problems

easy solution c++ Peak element

#include <bits/stdc++.h>
int findPeakElement(vector<int> &arr) {

  int n = arr.size();

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

      if( i ==0 && arr[i]> arr[i+1]){
          return i;
      }

      if(i ==(n-1) && arr[i]> arr[i-1]){
          return i;
      }
  }   
}
62 views
0 replies
0 upvotes

Interview problems

Easiest Binary Search Approach

int findPeakElement(vector<int> &arr) {

    int n = arr.size();

    if(n == 1) return 0;

    if(arr[0] > arr[1]) return 0; // If the peak is first element 

    if(arr[n - 1] > arr[n - 2]) return n - 1; //  If the peak is last element

 

    int low = 1;

    long long high = n - 2;

    while(low <= high) {

        int mid = (low + high) / 2;

        // If the mid element is a peak element

        if(arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {

            return mid;

        }

        // If the mid is in left half it means peak is in right half

        if(arr[mid] < arr[mid + 1]) {

            low = mid + 1;

        }

        // If the mid is in right half it means peak is in left half

        else {

            high = mid - 1;

        }

    }

    return -1;

}

 

66 views
0 replies
0 upvotes

Interview problems

Java Solution

import java.util.ArrayList;

public class Solution {

    public static int findPeakElement(ArrayList<Integer> arr) {

        // Write your code here.

        int n=arr.size();

        if(arr.size()==1){

            return 0;

        }

        if(arr.get(0)>arr.get(1)){

            return 0;

        }

        if(arr.get(n-1)>arr.get(n-2)){

            return n-1;

        }

        int start=1;

        int end=n-2;

        while(end>=start){

            int mid=start+(end-start)/2;

            if(arr.get(mid)>arr.get(mid-1) && arr.get(mid)>arr.get(mid+1)){

                return mid;

            }

            else if(arr.get(mid)>arr.get(mid+1) && arr.get(mid)<arr.get(mid-1)){

                end=mid-1;

            }

            else{

                start=mid+1;

            }

        }

          return -1;

    }

};

52 views
0 replies
0 upvotes

Interview problems

python solution

def findPeakElement(arr: [int]) -> int:

    # Write your code here

    for i in range(1,len(arr)-1,1):

        if arr[i-1] < arr[i] > arr[i+1]:

            return i

        if arr[0] > arr[1]:

            return 0

        if arr[-1] > arr[-2]:

            return len(arr) - 1

    pass

 

17 views
0 replies
0 upvotes

Interview problems

Find Peak Element

Time Complexity

The time complexity of the findPeakElement function is O(log⁡n)O(\log n)O(logn).

Explanation:

Binary Search Approach:

  • The algorithm uses a binary search technique to find a peak element. The search space is repeatedly halved by comparing the middle element with its right neighbor.
  • If the middle element is less than the next element (arr[mid] < arr[mid + 1]), then there is a peak on the right side of the array. Hence, the search space is reduced to the right half (s = mid + 1).
  • If the middle element is greater than or equal to the next element, there is a peak on the left side or at the current position. Hence, the search space is reduced to the left half (e = mid).
  • The search continues until s equals e, which will be the index of a peak element.

Logarithmic Time:

  • Since each step of the while loop effectively halves the search space, the number of iterations is proportional to log⁡n\log nlogn, where nnn is the number of elements in the array.
  • Therefore, the time complexity is O(log⁡n)O(\log n)O(logn).
Correctness:
  • The algorithm guarantees finding a peak element because at least one peak must exist in the array. By always moving towards a peak (based on the comparison between arr[mid] and arr[mid + 1]), the algorithm narrows down the search space to the location of a peak.
Example:

For an array like [1, 2, 3, 1], the algorithm will find 3 as a peak element, as it satisfies the condition of being greater than its neighbors.

Summary:
  • Time Complexity: O(log⁡n)O(\log n)O(logn)
  • Space Complexity: O(1)O(1)O(1) (since only a few extra variables are used)

This makes the algorithm both time and space efficient for finding a peak element in an array.

algorithms

35 views
0 replies
0 upvotes
Full screen
Console