Medium
Find Peak Element
👶 The 5-Year-Old Summary
Find a mountain peak in an array! A peak is bigger than its neighbors. You can see the whole array - find any peak quickly!
🎮 Interactive Visualizer
Array: [1, 2, 3, 1]
🧠 The Brain Hack
If nums[mid] < nums[mid+1], there's a peak on the RIGHT side! Go there! Otherwise, the peak is on the LEFT (or at mid)!
💻 The Clean Solution
def find_peak(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
# If going up, peak is to the right
if nums[mid] < nums[mid + 1]:
left = mid + 1
# Otherwise, peak is here or to left
else:
right = mid
return left # Or right, they're the same!
# [1, 2, 3, 1] → peak at index 2 (value 3)
Time: O(log n)
Space: O(1)