Find the first and last index of a target in a sorted array with duplicates. From a linear scan, to finding any copy and walking outwards (O(log n + k), which is O(n) when everything is equal), to two boundary searches: the first value ≥ target and the first value > target. Then counting occurrences, counting values in a range, float keys, and slicing a sorted log by time.
about 10 min 4 Python examples 2 quick checks
Problem. Given a sorted array nums (duplicates allowed) and a target, return [first, last], the first and
last index of target, or [-1, -1] if it's absent. Must run in O(log n).
ML context. A sorted array with duplicates is a sorted log: events sorted by timestamp, predictions sorted by
score, rows sorted by user id. "All rows for user 42", "all events in this minute", "how many predictions scored
between 0.7 and 0.8" are first-and-last questions, answered with two binary searches and a slice, without scanning.
1. Step 1: Clarify
That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson
Unlock "First and Last Position of an Element"
The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.
Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied