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] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000-231 <= nums[i] <= 231 - 1nums[i] != nums[i + 1] for all valid i.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are looking at a line of hills of different heights and need to find a hill that is higher than its immediate neighbors. The brute force approach involves walking down the entire line and checking each hill one by one to see if it fits the requirement.
Here's how the algorithm would work step-by-step:
def find_peak_element(hill_heights): total_hills = len(hill_heights) # Check every hill sequentially because brute force requires inspecting each element for current_index in range(total_hills): left_is_lower = current_index == 0 or hill_heights[current_index] > hill_heights[current_index - 1] right_is_lower = current_index == total_hills - 1 or hill_heights[current_index] > hill_heights[current_index + 1] # Stop immediately when we find a hill taller than both immediate neighbors if left_is_lower and right_is_lower: return current_index # Fallback return in case no peak condition is met during traversal return 0Instead of checking every single item one by one, the optimal approach uses a smart guessing strategy similar to finding a word in a dictionary by constantly cutting the search area in half. By looking at the immediate neighbors of a chosen spot, we can always guarantee that at least one peak is hiding on the side that goes uphill.
Here's how the algorithm would work step-by-step:
def find_peak_element(integer_array):
left_boundary = 0
right_boundary = len(integer_array) - 1
while left_boundary < right_boundary:
middle_index = (left_boundary + right_boundary) // 2
# Compare middle element with its right neighbor to determine the slope direction.
if integer_array[middle_index] < integer_array[middle_index + 1]:
left_boundary = middle_index + 1
else:
right_boundary = middle_index
# The search space converges to a single index representing a valid peak element.
return left_boundary| Case | How to Handle |
|---|---|
| Single-element array | Return index zero immediately since the sole element is trivially greater than its out-of-bounds imaginary negative infinity neighbors. |
| Two-element strictly increasing or decreasing array | Binary search correctly identifies the boundary element as the peak by comparing the two values and following the slope. |
| Array sorted in strictly ascending order | The binary search naturally migrates to the right boundary, correctly identifying the final element as a peak. |
| Array sorted in strictly descending order | The binary search migrates to the left boundary, correctly identifying the first element as a peak. |
| Array with multiple peaks | Binary search guarantees finding at least one valid peak by moving toward whichever neighbor is strictly greater. |
| Array containing negative numbers and zeros | The relative greater-than comparisons function identically across negative and positive domains without requiring offset adjustments. |
| Maximum-sized inputs up to constraints limit | O(log n) binary search executes efficiently within logarithmic time and constant O(1) space, avoiding memory limits. |
| Midpoint calculation with extreme array lengths | Using the bitwise shift or low plus high minus low divided by two prevents potential integer overflow during index addition. |