Peak Element
š Problem Statement
A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = -ā and nums[n] = -ā.
Input: nums = [1, 2, 1, 3, 5, 6, 4] -> Output: 1 or 5.
Constraint: You must write an algorithm that runs in time.
š” Intuition
We can find a peak by treating the array as a mountain range and following the upward slope. If we drop onto a random point mid and see that the next step mid + 1 is higher, we are walking uphill, meaning there must be a peak to our right. Conversely, if mid + 1 is lower, we are on a downward slope, meaning there must be a peak to our left (or mid itself is the peak). By always moving towards the higher ground, we can eliminate half the mountain at every step using Binary Search, even though the array is not globally sorted.
š§ Approach
- Initialize two pointers:
left = 0andright = len(nums) - 1. - Run a
whileloop as long asleft < right. - Calculate the
midpoint. - Compare
arr[mid]to its right neighborarr[mid + 1]. - If
arr[mid] < arr[mid + 1](ascending slope), the peak is to the right. Setleft = mid + 1. - If
arr[mid] > arr[mid + 1](descending slope), the peak is atmidor to its left. Setright = mid. - When the loop terminates (
left == right), the pointers will have converged on a peak. Returnleft.
ā” Complexity Analysis
ā We divide the search space in half during every iteration, vastly outperforming a linear scan.
ā We only use a few integer variables (left, right, mid) to track our position.
ā ļø Common Mistakes
- Using
left <= rightin thewhileloop condition. Because we are accessingarr[mid + 1], a<=condition can cause anIndexErrorwhenleftandrightconverge on the last element. - Setting
right = mid - 1whenarr[mid] > arr[mid + 1]. Ifmidis the peak, subtracting 1 will skip over it.rightmust be set tomidto keep the potential peak inside the search space. - Overcomplicating the logic by checking both
arr[mid - 1]andarr[mid + 1]. You only need to check one direction to determine the slope!
šÆ Final Thoughts
This problem shatters the common misconception that Binary Search only works on fully sorted arrays. The true requirement for Binary Search is simply that we have a reliable way to eliminate half of the search space at each step. By leveraging local gradients (slopes), we can apply efficiency to seemingly chaotic data.