Tutorialspoint
Problem
Solution
Submissions

Peak Element in a List

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

Write a Python program to find a peak element in an array. A peak element is an element that is 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:
    • We need to find an element greater than its neighbors.
    • Element at index 2 is 20, which is greater than its left neighbor 3 and right neighbor 4.
    • Therefore, index 2 is a peak element.
Example 2
  • Input: arr = [1, 2, 3, 1]
  • Output: 2
  • Explanation:
    • We need to find an element greater than its neighbors.
    • Element at index 2 is 3, which is greater than its left neighbor 2 and right neighbor 1.
    • Therefore, index 2 is a peak element.
Constraints
  • 1 ≤ arr.length ≤ 1000
  • -2^31 ≤ arr[i] ≤ 2^31 - 1
  • arr[i] != arr[i + 1] for all valid i
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysGoogleeBay
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 separately

Steps to solve by this approach:

 Step 1: Initialize left and right pointers to start and end of array.
 Step 2: Calculate middle index using binary search approach.
 Step 3: Compare middle element with its right neighbor.
 Step 4: If middle element is greater than right neighbor, search left half.
 Step 5: If right neighbor is greater, search right half.
 Step 6: Continue until left and right pointers meet.
 Step 7: Return the final position as peak element index.

Submitted Code :