Find First and Last Position of Element in Sorted Array (LeetCode 34): Solution and Explanation
Given an array sorted in non-decreasing order and a target value, return the index of the target's first occurrence and its last occurrence. If the target does not appear, return [-1, -1]. The solution is expected to run in O(log n) time.
Watch it run step by step
Try your own input and write the code →Intuition
The simple approach walks the array once, recording the first index that equals the target and the last one. That is O(n), which misses the logarithmic requirement. A tempting middle ground is to binary search for any copy of the target and then walk left and right to find the ends, but if the array is mostly the target, that walk is O(n) again.
The better idea is to recognize that you are searching for two boundaries, not one value. The first occurrence is the leftmost index where nums[i] >= target holds and the value equals the target. The last occurrence is the rightmost index where nums[i] <= target holds and the value equals the target. Each of those is a classic binary search on a monotone condition.
The only change from ordinary binary search is what happens when you find a match. Instead of returning immediately, you remember the index as a candidate and keep searching in the direction of the boundary you want: left for the first occurrence, right for the last. The search continues to halve the range, so each one finishes in O(log n), and the last candidate you recorded is the true boundary.
Approach: Two boundary binary searches
- Write
findFirstwithleft = 0,right = len(nums) - 1andresult = -1. - In
findFirst, computemid. Ifnums[mid] >= target, recordmidwhen it equals the target, then setright = mid - 1to keep looking left. Otherwise setleft = mid + 1. - Write
findLastthe same way, but branch onnums[mid] <= target. Record a match and moveleft = mid + 1to keep looking right; otherwise setright = mid - 1. - Both loops run while
left <= rightand return the last recorded candidate, or -1 if none matched. - Return
[findFirst(), findLast()].
Step-by-step example
nums = [5,7,7,8,8,10], target = 8
findFirststarts withleft = 0andright = 5.mid = 2holds 7, which is less than 8, soleftbecomes 3.mid = 4holds 8. It is a match, soresult = 4, andrightbecomes 3 to look further left.mid = 3holds 8 again, soresult = 3andrightbecomes 2. The loop ends and the first position is 3.findLaststarts the same way.mid = 2holds 7, which is at most 8, soleftbecomes 3.mid = 4holds 8, soresult = 4andleftbecomes 5.mid = 5holds 10, which is greater, sorightbecomes 4. The loop ends and the answer is [3, 4].
Code: Python, Java, C++
1class Solution:
2 def searchRange(self, nums: List[int], target: int) -> List[int]:
3 def findFirst():
4 left, right = 0, len(nums) - 1
5 result = -1
6 while left <= right:
7 mid = (left + right) // 2
8 if nums[mid] >= target:
9 if nums[mid] == target:
10 result = mid
11 right = mid - 1
12 else:
13 left = mid + 1
14 return result
15
16 def findLast():
17 left, right = 0, len(nums) - 1
18 result = -1
19 while left <= right:
20 mid = (left + right) // 2
21 if nums[mid] <= target:
22 if nums[mid] == target:
23 result = mid
24 left = mid + 1
25 else:
26 right = mid - 1
27 return result
28
29 return [findFirst(), findLast()]1class Solution {
2 public int[] searchRange(int[] nums, int target) {
3 return new int[]{findFirst(nums, target), findLast(nums, target)};
4 }
5
6 private int findFirst(int[] nums, int target) {
7 int left = 0, right = nums.length - 1, result = -1;
8 while (left <= right) {
9 int mid = left + (right - left) / 2;
10 if (nums[mid] >= target) {
11 if (nums[mid] == target) result = mid;
12 right = mid - 1;
13 } else {
14 left = mid + 1;
15 }
16 }
17 return result;
18 }
19
20 private int findLast(int[] nums, int target) {
21 int left = 0, right = nums.length - 1, result = -1;
22 while (left <= right) {
23 int mid = left + (right - left) / 2;
24 if (nums[mid] <= target) {
25 if (nums[mid] == target) result = mid;
26 left = mid + 1;
27 } else {
28 right = mid - 1;
29 }
30 }
31 return result;
32 }
33}1class Solution {
2public:
3 vector<int> searchRange(vector<int>& nums, int target) {
4 return {findFirst(nums, target), findLast(nums, target)};
5 }
6
7 int findFirst(vector<int>& nums, int target) {
8 int left = 0, right = nums.size() - 1, result = -1;
9 while (left <= right) {
10 int mid = left + (right - left) / 2;
11 if (nums[mid] >= target) {
12 if (nums[mid] == target) result = mid;
13 right = mid - 1;
14 } else {
15 left = mid + 1;
16 }
17 }
18 return result;
19 }
20
21 int findLast(vector<int>& nums, int target) {
22 int left = 0, right = nums.size() - 1, result = -1;
23 while (left <= right) {
24 int mid = left + (right - left) / 2;
25 if (nums[mid] <= target) {
26 if (nums[mid] == target) result = mid;
27 left = mid + 1;
28 } else {
29 right = mid - 1;
30 }
31 }
32 return result;
33 }
34};Time and space complexity
O(log n)
Each of the two searches halves its range on every iteration, so together they take about 2 log n steps.
O(1)
Only a few index variables are used in each helper.
Other approaches
Lower bound twice (time O(log n), space O(1))
Use one lower-bound search that returns the first index with nums[i] >= x. The first position is lower_bound(target), and the last is lower_bound(target + 1) - 1, after checking that the target exists. In Python, bisect_left and bisect_right do exactly this.
Linear scan (time O(n), space O(1))
Walk the array once and record the first and last indices that match. It is trivial to write and fine for small inputs, but it does not meet the logarithmic requirement.
Common mistakes
- Returning as soon as
nums[mid] == target. That finds some occurrence, not necessarily the first or last one. - Expanding outward linearly from a found match. On an array full of the target value this degrades to O(n).
- Using
left < rightwithright = mid - 1, which can skip the final candidate. Pairleft <= rightwith themid - 1andmid + 1updates consistently. - Forgetting the empty array. With
right = -1the loops do not run and both helpers return -1, which is correct, but code that readsnums[0]first will crash.
Frequently asked questions
Why not just use one binary search and scan outward?
If the target repeats many times, the outward scan touches every copy, making the worst case O(n). Two boundary searches keep the guarantee at O(log n) regardless of how many duplicates exist.
Can this be done with a single binary search?
Not cleanly. The two boundaries are independent, so you need two searches, but each is O(log n), and two logarithmic searches are still O(log n) overall.
How does bisect relate to this problem?
bisect_left(nums, target) returns the first index where the target could be inserted, which is the first occurrence if it exists, and bisect_right(nums, target) - 1 is the last occurrence. The custom helpers here implement the same logic by hand.
What if the target is not in the array?
Neither helper ever records a match, so both return -1 and the answer is [-1, -1].