Find First and Last Position of Element in Sorted Array
Problem Statement
You are given an array nums sorted from smallest to largest. Values can repeat. You are also given a number target.
Return the first and last index where target appears, as [first, last]. If target doesn't appear at all, return [-1, -1].
Your solution must run in O(log n) time.
A sorted integer array nums (possibly with duplicates, possibly empty) and an integer target.
[first, last] β the leftmost and rightmost positions of target, or [-1, -1] if it's absent.
The two 8s are at indexes 3 and 4.
There is no 6 in the array.
An empty array contains nothing.
- β’ 0 β€ nums.length β€ 10^5
- β’ β10^9 β€ nums[i] β€ 10^9
- β’ nums is sorted in non-decreasing order
- β’ β10^9 β€ target β€ 10^9
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Walk left to right; record the first and last match
Binary search for any copy, then walk left and right to the edges
First index β₯ target, and first index > target minus 1
Go through every element. The first time you see target, save its index as first. Every time you see it, update last.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Binary Search translate into production architectures and low-level memory mechanics.