MemotivaLeetCode Patterns Flashcards: Binary Search, Search Space, Templates, Edge Cases

How does binary search apply to finding the peak element in an array?

Nortren·

How does binary search apply to finding the peak element in an array?

0:24

A peak element is greater than its neighbors. Compare the mid element with mid plus one. If mid is greater, a peak exists on the left side including mid, so set right to mid. If mid plus one is greater, a peak exists on the right side, so set left to mid plus one. This works because if you are going uphill, there must be a peak ahead or at the end. The loop converges when left equals right, pointing to a peak. This finds any peak, not necessarily the global maximum. ---
neetcode.io