DSA AnimatorDSA animations
Find First and Last Position LC #34 Medium Binary Search · Left/Right Bound
Problem

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.

Example 1
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Explanation: 8 first appears at index 3, last at index 4.
Example 2
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Explanation: 6 not found in array.
Example 3
Input: nums = [1], target = 1
Output: [0,0]
Explanation: Single element array; first and last are both index 0.
Constraints: 0 ≤ nums.length ≤ 10⁵  |  −10⁹ ≤ nums[i], target ≤ 10⁹  |  nums sorted in non-decreasing order
Try Examples
Custom:
Array
Initializing
Variables
Phase
—
lo
—
hi
—
mid
—
nums[mid]
—
bound
—
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Run Search #1 (left bound): binary search, on match record bound=mid then continue left hi=mid−1
2
During left search: nums[mid] < target → lo=mid+1  |  nums[mid] > target → hi=mid−1
3
Run Search #2 (right bound): on match record bound=mid then continue right lo=mid+1
4
Return [first, last]. Both are -1 if target not found.
Time
O(log n)
Space
O(1)
Why Two Searches?

A single binary search stops as soon as it finds the target — but there may be duplicates. By not stopping on the first match and instead recording the index and shrinking the search window toward the boundary, each search converges on the extreme position. Two passes of O(log n) remain O(log n) overall.

How to solve Find First and Last Position of Element

LeetCode 34 · Medium · Binary Search · Pattern: Binary Search Bounds

Why the obvious approach is slow

Finding one 8 and then walking left and right is O(n) if there are many copies. Two binary searches keep it logarithmic.

The key idea

Run binary search twice. To find the first index, when you hit the target, record it and keep searching left. To find the last index, record it and keep searching right.

Remember

On a match, record it and keep searching toward the boundary you want. Two binary searches give the first and the last position.

Run the animation above on your own input, or watch the 1:28 video explanation of Find First and Last Position of Element with a dry run and Java code.

More Binary Search problems