← Binary Search

Pattern Recognition Drill

#53 — First and last occurrence

Medium Binary Search

The Problem

Given a sorted array with duplicates and a target, find the first and last index of the target.

What approach would you use?

Think about it before scrolling down.

Key Signals

Binary Search

Run bisect_left (find first >=) and bisect_right (find first >) separately. Both O(log n).

Common Trap

A single binary search that finds one occurrence then scans linearly is O(n) worst case for all-same arrays.

← #52 #54 →