#34
Medium
Binary Search

Find First and Last Position

Return the first and last index of a target in a sorted array.

ArrayBinary Search

Pattern fit

This is the cleanest left-boundary and right-boundary binary-search question because the array is already sorted and the target condition is obvious.

Key observation

The left boundary and right boundary are two different predicates and deserve two separate searches.

Target complexity

O(log n) / O(1)

How to break down the solution cleanly

1

This is the cleanest left-boundary and right-boundary binary-search question because the array is already sorted and the target condition is obvious.

2

The left boundary and right boundary are two different predicates and deserve two separate searches.

3

Write the monotonic predicate in plain English first.

4

Choose a search interval that definitely contains the answer.

Reference implementation

Python
# Generic pattern template
# Find first position where check(mid) is true
left, right = 0, n
while left < right:
    mid = left + (right - left) // 2
    if check(mid):
        right = mid
    else:
        left = mid + 1
return left

Common pitfalls

warning

Trying to get both answers in one binary search and making logic fragile.

warning

Returning the first found mid as if it were a boundary.

Common follow-ups

Can you express each search as first true?

How would the answer change if the target did not exist?

Continue with related problems

Build repeatable depth inside the Binary Search cluster before moving on.

view_weekBack to the pattern page
LeetCode 34. Find First and Last Position Guide | Interview AiBox