AlgoMaster Logo

Find Peak Element

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Linear Scan

Intuition:

The simplest approach to find a peak element is to iterate through the array and look for an element that is greater than its neighbors. This is a straightforward solution where we check each element to see if it meets the peak condition.

Steps:

  • Iterate through the array.
  • For each element nums[i], check if it is greater than its neighbors.
  • Return the index of the first peak element found.

Code:

Intuition:

To achieve a more efficient solution, use a modified binary search. Since we know that a peak exists and elements decrease at the peak (or reach the end of the array), we can utilize this fact to efficiently find a peak in logarithmic time.

Steps:

  • Utilize a binary search approach where you check the middle element.
  • If the middle element is greater than the next element, then a peak must exist on the left side (including mid).
  • If it is less than the next element, then a peak must exist on the right side.
  • Narrow the search to the half where the peak is more probable.

Code: