Find First and Last Position of Element in Sorted Array
Problem
You are given an array of integers nums sorted in non-decreasing order and a value target. Return a two-element list [first, last] giving the smallest and largest indices at which target appears. If target is not present, return [-1, -1]. The running time should stay logarithmic even when every element equals target.
numsmay be empty and has at most 200,000 elements.- Values and
targetare integers between -2,000,000,000 and 2,000,000,000.
Examples
nums = [3, 6, 6, 6, 9, 14], target = 6→[1, 3].nums = [3, 6, 6, 6, 9, 14], target = 10→[-1, -1]; 10 is absent.nums = [4, 4, 4, 4, 4], target = 4→[0, 4]. When the whole array is the target, a naive "find it then expand outward" approach degrades to O(n).
Hints
- A standard binary search stops at any occurrence. Why is expanding from there to find the ends not O(log n)?
- Rather than searching for the value, search for a boundary: the first index whose element is
>= target. - Two lower-bound searches: one for
targetand one fortarget + 1. The second minus one is the last position.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.