Understanding the Problem
A peak element in an array is one that is not smaller than its neighbors. That means at index i
, the value arr[i]
is a peak if it satisfies one of the following conditions:
- It is the first element and
arr[0] ≥ arr[1]
- It is the last element and
arr[n-1] ≥ arr[n-2]
- It is in the middle and
arr[i] ≥ arr[i-1]
and arr[i] ≥ arr[i+1]
The goal is to efficiently find any one peak. Note: multiple peaks may exist, but we only need to find one of them.
Step-by-Step Solution with Example
Step 1: Start with an example
Let’s take the array [1, 3, 20, 4, 1, 0]
. Visually, it looks like:
Index: 0 1 2 3 4 5
Value: 1 3 20 4 1 0
Here, 20
at index 2
is clearly greater than both 3
and 4
, so it's a peak.
Step 2: Use Binary Search for Efficiency
We don’t need to linearly scan the entire array. A binary search approach gives us O(log n)
efficiency:
- Set
low = 0
, high = n - 1
- While
low ≤ high
:
- Compute
mid = (low + high) / 2
- Check if
arr[mid]
is a peak
- If
arr[mid] < arr[mid + 1]
, search the right half
- Else if
arr[mid] < arr[mid - 1]
, search the left half
- Else return
mid
as the peak
Step 3: Apply Binary Search to Our Example
- Initial range:
low = 0
, high = 5
mid = 2
→ arr[2] = 20
- Check neighbors:
arr[1] = 3
and arr[3] = 4
20 ≥ 3
and 20 ≥ 4
→ it's a peak!
So, index 2
is returned. No further searching is needed.
Edge Cases
Case 1: Array has only one element
Example: [7]
— This is automatically a peak as it has no neighbors.
Case 2: Peak is at the beginning
Example: [10, 5, 2]
— Here, 10 ≥ 5
, so index 0
is a peak.
Case 3: Peak is at the end
Example: [1, 2, 4]
— 4 ≥ 2
, so index 2
is a peak.
Case 4: Empty array
If arr.length == 0
, there's no element to evaluate. We should return -1
to indicate no peak.
Finally
By understanding the definition of a peak and applying a smart binary search strategy, we can find any one peak efficiently in O(log n)
time. Always check edge cases like an empty array, a single-element array, or peaks at the boundaries to make your solution robust.
And remember: we don’t need to find the highest peak — just any one that satisfies the peak condition!
Comments
Loading comments...