Loading section...

First and Last Occurrence

Concepts: pyBinarySearchFirst, pyBinarySearchLast

Finding the first and last occurrence of a target in a sorted array (LeetCode 34: Find First and Last Position of Element in Sorted Array) is the canonical binary search variant question. Nearly every company that asks binary search will ask this or a direct derivative. The naive approach runs two separate binary searches. The subtle approach modifies a single template. You need to know both and understand the difference in how you handle mid == target. Finding the Leftmost (First) Occurrence When nums[mid] == target, you do NOT return immediately. Instead, you record mid as a potential answer and continue searching left. This is the key difference from a standard binary search. You set right = mid - 1 even when you find the target, because there might be an earlier occurrence to the left.