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

How do you find the first or last occurrence of a target using binary search?

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

Аудио-карточка · 0:24

Nortren·

How do you find the first or last occurrence of a target using binary search?

0:24

Standard binary search stops at any occurrence. To find the first occurrence, when you find the target at mid, do not return immediately. Instead, record mid as a candidate and continue searching the left half by setting right to mid minus one. To find the last occurrence, record mid and continue searching the right half by setting left to mid plus one. After the loop ends, return the recorded candidate. This ensures you find the boundary occurrence rather than an arbitrary one.
neetcode.io