Tutorialspoint
Problem
Solution
Submissions

Peak Element in an Array

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

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. If the array contains multiple peaks, return the index of any peak element.

For boundary elements (first and last), we only compare with the one neighbor they have.

Example 1
  • Input: nums = [1,2,3,1]
  • Output: 2
  • Explanation:
    • Index 2 is a peak because nums[2] = 3 is greater than its neighbors nums[1] = 2 and nums[3] = 1.
Example 2
  • Input: nums = [1,2,1,3,5,6,4]
  • Output: 5
  • Explanation:
    • Index 5 is a peak because nums[5] = 6 is greater than its neighbors nums[4] = 5 and nums[6] = 4.
    • Index 2 is also a peak (nums[2] = 1), but we only need to return one peak index.
Constraints
  • 1 ≤ nums.length ≤ 1000
  • -2^31 ≤ nums[i] ≤ 2^31 - 1
  • nums[i] != nums[i+1] for all valid i
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsGoldman SachsPhillips
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

  • A naive approach would be to scan the entire array linearly and check each element
  • Can we use binary search to improve the time complexity?
  • During binary search, we can determine which half of the array must contain a peak
  • Check the middle element and its neighbors to determine search direction
  • Remember to handle edge cases for boundary elements

Steps to solve by this approach:

 Step 1: Use binary search to efficiently find a peak element in logarithmic time.

 Step 2: Initialize two pointers, left and right, pointing to the start and end of the array.
 Step 3: In each iteration, calculate the middle index and compare the middle element with its right neighbor.
 Step 4: If the middle element is greater than its right neighbor, a peak exists in the left half (including mid).
 Step 5: If the middle element is less than its right neighbor, a peak exists in the right half.
 Step 6: Continue narrowing the search space until left and right pointers meet.
 Step 7: Return the final index, which will be a peak element.

Submitted Code :