Tutorialspoint
Problem
Solution
Submissions

Find Peak Element

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find a peak element in an array. A peak element is an element that is strictly greater than its neighbors. For corner elements, we need to consider only one neighbor. The array may contain multiple peaks, in that case return the index of any one of them.

Example 1
  • Input: arr[] = {1, 3, 20, 4, 1, 0}
  • Output: 2
  • Explanation: Element at index 2 is 20. 20 is greater than its left neighbor 3 and right neighbor 4. Therefore, index 2 is a peak element.
Example 2
  • Input: arr[] = {5, 10, 20, 15}
  • Output: 2
  • Explanation: Element at index 2 is 20. 20 is greater than its left neighbor 10 and right neighbor 15. Therefore, index 2 is a peak element.
Constraints
  • 1 ≤ n ≤ 10^5
  • -2^31 ≤ arr[i] ≤ 2^31 - 1
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsPwCSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use binary search approach to find the peak element efficiently
  • Compare the middle element with its neighbors
  • If middle element is greater than both neighbors, it's a peak
  • If left neighbor is greater, search in the left half
  • If right neighbor is greater, search in the right half
  • Handle edge cases for first and last elements

Steps to solve by this approach:

 Step 1: Handle edge cases - single element array, first element, and last element
 Step 2: Initialize binary search boundaries (left = 1, right = n-2)
 Step 3: Find middle element and compare with its neighbors
 Step 4: If middle element is greater than both neighbors, return its index
 Step 5: If left neighbor is greater, search in the left half
 Step 6: If right neighbor is greater, search in the right half
 Step 7: Continue until peak element is found

Submitted Code :