Find First and Last Position of Element in Sorted Array
On this page
Problem statement
Given an array of integers sorted in non-decreasing order and a target value, return the first and last index at which the target appears, as
[first, last]. If the target isn't in the array, return[-1, -1]. The solution must run in O(log n) time.
The best test of whether you can write a binary search that finds a boundary, not just "some match". Original problem: LeetCode 34.
Example
![The 4s occupy indexes 1 to 3. A target that isn't present, like 5, gives [−1, −1].](https://storage.ghost.io/c/cc/3d/cc3dd2ec-1125-4515-87dd-11389c0d3c50/content/images/2026/11/000-41d590d3-15.png)
Input: nums = [2, 4, 4, 4, 7, 9], target = 4 -> [1, 3]
Input: nums = [2, 4, 4, 4, 7, 9], target = 5 -> [-1, -1]
Input: nums = [2, 4, 4, 4, 7, 9], target = 9 -> [5, 5]
Input: nums = [], target = 3 -> [-1, -1]
Constraints (assumed)
- 0 ≤ n ≤ 10⁵; values are 32-bit integers; the array is sorted ascending.
What this question tests
- A binary search for the first position where a condition becomes true (lower bound).
- Reusing one helper instead of writing two slightly different searches.
- Bounds: empty arrays, targets outside the range, and loop termination.
Questions to ask first
- Is the array sorted ascending, with duplicates allowed? (Here: yes.)
- What to return when the target is missing? (Here:
[-1, -1].) - Is O(log n) required? (Here: yes; a linear scan is not accepted.)
- Can I use the library (
bisect,lower_bound,Arrays.binarySearch)? Often allowed after you've shown you can write it.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.