15% off all plans & roadmaps Use code
See plansFind First and Last Position of Element in Sorted Array
- LeetCode 34
- Medium
- Binary Search Patterns
- Find First/Last Occurrence
Updated
TL;DR: Given a sorted array, return the first and last index of a target, or [-1, -1] when it is missing. Two binary searches solve it in O(log n) time. One finds the first index with a value at least the target. The other finds the first index with a value above it.
Problem
You get an array of integers nums sorted in non-decreasing order. Find the first and last index where the value target appears.
If target does not appear in the array, return [-1, -1].
Your algorithm must run in O(log n) time.
Example 1
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3
Input: nums = [], target = 0 Output: [-1,-1]
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9numsis a non-decreasing array.-10^9 <= target <= 10^9
Constraints that matter
- With n up to 10^5, a linear scan is too slow for the required O(log n) bound, so every step must discard a large part of the array.
- The array is sorted, so all copies of
targetform one contiguous block. You only need the two edges of that block. - Values stay within 10^9 in size, so
target + 1still fits in a 32-bit signed integer. That makes a boundary search ontarget + 1safe. - The array can be empty. Check the length before you read
nums[first].
Hints
Hint 1
The sorted order is the key fact.
Hint 2
Check every index from left to right.
Solution
Intuition
The sorted order is the key fact. Every copy of target sits in one block, values left of the block are smaller, and values right of it are larger. Finding the two edges of that block is a boundary problem, and binary search solves boundary problems in logarithmic time.
Picture a sorted row of coat hooks, with all hooks of one size grouped together. The lowerBound search is a finger moving by halves to the first hook that is not smaller than the target.
This is the find first and last occurrence pattern. A plain binary search stops at the first match it sees, and that match can sit in the middle of the block. Change the question you ask at each probe, and you find an edge instead of a match.
Two edges mean two searches. The first index holding a value at least target is the start of the block. The first index holding a value greater than target is one past the end, so subtracting one gives the last index. If the start does not hold target, the block is empty and the answer is [-1, -1].
Worked example
Input: nums = [5, 7, 7, 8, 8, 10], target = 8 Output: [3, 4] Explanation: The value 8 sits at indices 3 and 4. Index 2 holds a 7 and index 5 holds a 10, so the block of 8s starts at 3 and ends at 4.
Approach 1: Brute force
Check every index from left to right. Keep the first index where the value equals target, and move last forward on every later match. The scan never stops early, so it reads all n values even though the array is sorted.
Steps
- Set
firstandlastto -1. - Loop
ifrom 0 to n - 1. - If
nums[i]equalstargetandfirstis still -1, setfirsttoi. - If
nums[i]equalstarget, setlasttoi. - Return
[first, last].
Dry run
Start with first = -1 and last = -1, using nums = [5, 7, 7, 8, 8, 10] and target = 8.
- i = 0: 5 is not 8. No change.
- i = 1: 7 is not 8. No change.
- i = 2: 7 is not 8. No change.
- i = 3: 8 matches.
firstis -1, sofirst = 3.last = 3. - i = 4: 8 matches.
firststays 3.last = 4. - i = 5: 10 is not 8. No change.
The scan ends with [3, 4].
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the array length. The loop runs once per index, and each iteration does a constant amount of work, so the total is n constant-time steps. The loop cannot stop early, because a match near the end can still move last. The extra space is two integers and the loop index.
PythonTested in our runner
from typing import List, Optional
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
first, last = -1, -1
for i in range(len(nums)):
if nums[i] == target:
if first == -1:
first = i
last = i
return [first, last]JavaTested in our runner
class Solution {
public int[] searchRange(int[] nums, int target) {
int first = -1;
int last = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
if (first == -1) {
first = i;
}
last = i;
}
}
return new int[]{first, last};
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int first = -1;
int last = -1;
for (int i = 0; i < (int)nums.size(); i++) {
if (nums[i] == target) {
if (first == -1) first = i;
last = i;
}
}
return {first, last};
}
};JavaScriptTested in our runner
var searchRange = function(nums, target) {
let first = -1;
let last = -1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) {
if (first === -1) first = i;
last = i;
}
}
return [first, last];
};GoTested in our runner
func searchRange(nums []int, target int) []int {
first, last := -1, -1
for i, v := range nums {
if v == target {
if first == -1 {
first = i
}
last = i
}
}
return []int{first, last}
}C#Tested in our runner
public class Solution {
public int[] searchRange(int[] nums, int target) {
int first = -1;
int last = -1;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] == target) {
if (first == -1) first = i;
last = i;
}
}
return new int[] { first, last };
}
}Approach 2: Binary search, then expand
What's slow: the brute force reads every element, but the sorted order tells you most positions cannot hold the target. The insight that fixes it: one binary search finds a single copy of target in O(log n) steps. Copies of the same value sit next to each other, so you can walk left and right from that copy until the value changes.
The walk costs one step per copy. That is cheap when the block is small, but it becomes the bottleneck when the block is large.
Steps
- Binary search for any index
foundwherenums[found]equalstarget. If there is none, return[-1, -1]. - Move
firstleft fromfoundwhile the value to its left still equalstarget. - Move
lastright fromfoundwhile the value to its right still equalstarget. - Return
[first, last].
Dry run
Use nums = [5, 7, 7, 8, 8, 10] and target = 8.
- Search: lo = 0, hi = 5, mid = 2. The value 7 is less than 8, so lo = 3.
- Search: lo = 3, hi = 5, mid = 4. The value 8 matches, so found = 4.
- Expand left: index 3 holds 8, so first = 3. Index 2 holds 7, so the walk stops.
- Expand right: index 5 holds 10, so the walk stops. last stays 4.
The result is [3, 4].
Complexity
| Time | O(log n + k) on average, O(n) in the worst case |
|---|---|
| Space | O(1) |
Let n be the array length and k the number of copies of target. The binary search makes at most about log2(n) + 1 probes. The two walks visit only positions that hold target, plus one stopping position each, so they cost O(k). When every value equals target, k equals n, so the total is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
lo, hi = 0, len(nums) - 1
found = -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
found = mid
break
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
if found == -1:
return [-1, -1]
first = found
while first > 0 and nums[first - 1] == target:
first -= 1
last = found
while last < len(nums) - 1 and nums[last + 1] == target:
last += 1
return [first, last]JavaTested in our runner
class Solution {
public int[] searchRange(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1;
int found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) {
found = mid;
break;
}
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found == -1) {
return new int[]{-1, -1};
}
int first = found;
while (first > 0 && nums[first - 1] == target) {
first--;
}
int last = found;
while (last < nums.length - 1 && nums[last + 1] == target) {
last++;
}
return new int[]{first, last};
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int lo = 0;
int hi = (int)nums.size() - 1;
int found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) {
found = mid;
break;
}
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found == -1) {
return {-1, -1};
}
int first = found;
while (first > 0 && nums[first - 1] == target) {
first--;
}
int last = found;
while (last < (int)nums.size() - 1 && nums[last + 1] == target) {
last++;
}
return {first, last};
}
};JavaScriptTested in our runner
var searchRange = function(nums, target) {
let lo = 0;
let hi = nums.length - 1;
let found = -1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] === target) {
found = mid;
break;
}
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found === -1) return [-1, -1];
let first = found;
while (first > 0 && nums[first - 1] === target) first--;
let last = found;
while (last < nums.length - 1 && nums[last + 1] === target) last++;
return [first, last];
};GoTested in our runner
func searchRange(nums []int, target int) []int {
lo, hi := 0, len(nums)-1
found := -1
for lo <= hi {
mid := lo + (hi-lo)/2
if nums[mid] == target {
found = mid
break
}
if nums[mid] < target {
lo = mid + 1
} else {
hi = mid - 1
}
}
if found == -1 {
return []int{-1, -1}
}
first := found
for first > 0 && nums[first-1] == target {
first--
}
last := found
for last < len(nums)-1 && nums[last+1] == target {
last++
}
return []int{first, last}
}C#Tested in our runner
public class Solution {
public int[] searchRange(int[] nums, int target) {
int lo = 0;
int hi = nums.Length - 1;
int found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) {
found = mid;
break;
}
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found == -1) {
return new int[] { -1, -1 };
}
int first = found;
while (first > 0 && nums[first - 1] == target) {
first--;
}
int last = found;
while (last < nums.Length - 1 && nums[last + 1] == target) {
last++;
}
return new int[] { first, last };
}
}The Find First/Last Occurrence infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Find First/Last Occurrence
Part of Binary Search Patterns
Approach 3: Two boundary searchesOptimalFind First/Last Occurrence
What's slow: the walk still touches every copy of target. With 10^5 copies, the walk alone costs 10^5 steps. The insight that fixes it: both edges of the block are boundary positions in a sorted array. Each edge is the first index where a test changes from false to true, so binary search finds it directly.
The start is the first index whose value is at least target. The end is one less than the first index whose value is greater than target. For integers, the second question equals the first question asked about target + 1, so one helper answers both.
Why it is correct. The test value at least x is false for every index before the answer and true for every index after it, because the array is sorted. Each probe either moves the left edge past a false index or pulls the right edge onto a true index, so the answer is never discarded. For integers, the first index above target is the first index at least target plus one, so subtracting one gives the last copy.
Steps
- Write
lowerBound(x)that returns the first index whose value is at leastx, or n if no such index exists. - Set
firsttolowerBound(target). - If
firstis n ornums[first]is nottarget, return[-1, -1]. - Set
lasttolowerBound(target + 1) - 1. - Return
[first, last].
Dry run
Use nums = [5, 7, 7, 8, 8, 10] and target = 8. The helper keeps a half-open range [lo, hi), starting with lo = 0 and hi = 6.
| Step | lo | hi | mid | nums[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 8 | 8 is not less than 8, so hi = 3 |
| 2 | 0 | 3 | 1 | 7 | 7 is less than 8, so lo = 2 |
| 3 | 2 | 3 | 2 | 7 | 7 is less than 8, so lo = 3 |
| 4 | 3 | 3 | none | none | lo equals hi, return 3 |
So first = 3, and nums[3] is 8, which matches. Now compute lowerBound(9).
| Step | lo | hi | mid | nums[mid] | Action |
|---|---|---|---|---|---|
| 5 | 0 | 6 | 3 | 8 | 8 is less than 9, so lo = 4 |
| 6 | 4 | 6 | 5 | 10 | 10 is not less than 9, so hi = 5 |
| 7 | 4 | 5 | 4 | 8 | 8 is less than 9, so lo = 5 |
| 8 | 5 | 5 | none | none | lo equals hi, return 5 |
So last = 5 - 1 = 4. The result is [3, 4].
For target = 6, lowerBound(6) returns 1. nums[1] is 7, so the answer is [-1, -1].
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the array length. Each iteration of lowerBound halves the range [lo, hi), so the helper runs about log2(n) + 1 iterations. The solution calls the helper at most twice, so the total is O(log n). The helper stores three integers, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def lower_bound(x: int) -> int:
# First index whose value is at least x, or len(nums) if none
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < x:
lo = mid + 1
else:
hi = mid
return lo
first = lower_bound(target)
if first == len(nums) or nums[first] != target:
return [-1, -1]
# First index above target, minus one, is the last copy of target
last = lower_bound(target + 1) - 1
return [first, last]JavaTested in our runner
class Solution {
public int[] searchRange(int[] nums, int target) {
int first = lowerBound(nums, target);
if (first == nums.length || nums[first] != target) {
return new int[]{-1, -1};
}
int last = lowerBound(nums, target + 1) - 1;
return new int[]{first, last};
}
private int lowerBound(int[] nums, int x) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int first = lowerBound(nums, target);
if (first == (int)nums.size() || nums[first] != target) {
return {-1, -1};
}
int last = lowerBound(nums, target + 1) - 1;
return {first, last};
}
private:
// First index whose value is at least x, or size if none
int lowerBound(const vector<int>& nums, int x) {
int lo = 0;
int hi = (int)nums.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
};JavaScriptTested in our runner
var searchRange = function(nums, target) {
// First index whose value is at least x, or nums.length if none
const lowerBound = (x) => {
let lo = 0;
let hi = nums.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
};
const first = lowerBound(target);
if (first === nums.length || nums[first] !== target) return [-1, -1];
const last = lowerBound(target + 1) - 1;
return [first, last];
};GoTested in our runner
func searchRange(nums []int, target int) []int {
// First index whose value is at least x, or len(nums) if none
lowerBound := func(x int) int {
lo, hi := 0, len(nums)
for lo < hi {
mid := lo + (hi-lo)/2
if nums[mid] < x {
lo = mid + 1
} else {
hi = mid
}
}
return lo
}
first := lowerBound(target)
if first == len(nums) || nums[first] != target {
return []int{-1, -1}
}
last := lowerBound(target+1) - 1
return []int{first, last}
}C#Tested in our runner
public class Solution {
public int[] searchRange(int[] nums, int target) {
int first = LowerBound(nums, target);
if (first == nums.Length || nums[first] != target) {
return new int[] { -1, -1 };
}
int last = LowerBound(nums, target + 1) - 1;
return new int[] { first, last };
}
// First index whose value is at least x, or Length if none
private static int LowerBound(int[] nums, int x) {
int lo = 0;
int hi = nums.Length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
}Common mistakes
return midthe momentnums[mid] == target. This returns any copy of the value, often one in the middle of the block. Keep searching, or use the two boundary searches.hi = mid - 1inside the lower bound whennums[mid] >= x. This discardsmid, which may be the first copy. Sethi = midso the candidate stays in range.lo = midwhennums[mid] < x. The range never shrinks whenhi = lo + 1, and the loop runs forever. Uselo = mid + 1.- Returning
[first, last]without checkingnums[first] == target. Fortarget = 6in the sample array, the code returns[1, 0]instead of[-1, -1]. last = lowerBound(target) - 1. That computes the index before the first copy, not the last copy. The end must come from the search ontarget + 1.mid = (lo + hi) / 2in Java, C++ or C#. With the array bounds given here it does not overflow, butlo + (hi - lo) / 2is the safe habit and costs nothing.
Edge cases
nums = [],target = 0: return[-1, -1]. The bounds check must run before any read ofnums[first].nums = [4],target = 4: return[0, 0]. The block has one element.nums = [2, 2, 2, 2],target = 2: return[0, 3]. Every value matches, so the expanding walk visits all four positions.nums = [5, 7, 7],target = 1: return[-1, -1]. The lower bound is 0, andnums[0]is 5, not 1.nums = [5, 7, 7],target = 9: return[-1, -1]. The lower bound is n, so the code must checkfirst == nfirst.nums = [-1000000000, 0, 1000000000],target = 1000000000: return[2, 2]. Large values stay inside 32-bit range, andtarget + 1does not overflow.
Follow-ups interviewers ask
- How would you count how many times target appears?
- Subtract the two boundaries:
lowerBound(target + 1) - lowerBound(target). If target is missing, both calls return the same index, so the result is 0 without a special case. The cost stays O(log n). - What if the array is not sorted?
- Binary search no longer applies, because copies of target can be spread across the array. One linear scan can record the smallest and largest index where the value appears, which costs O(n) time and O(1) extra space. Sorting a copy would lose the original indices, so it does not solve the same question.
- What if the array is too large to fit in memory?
- If the data sits on disk in fixed-size blocks, you can binary search over block offsets. Each probe reads one block, so the search reads O(log n) blocks. If the data is a stream you cannot seek through, scan it once and keep the first and last matching indices, which uses O(n) time and O(1) memory.
Find First and Last Position of Element in Sorted Array FAQ
What is the time complexity of Find First and Last Position of Element in Sorted Array?
The optimal solution runs in O(log n) time, where n is the array length. It makes two boundary searches, and each one halves the search range at every step. The extra space is O(1).
Why use binary search for Find First and Last Position of Element in Sorted Array?
The array is sorted, so the test 'value is at least x' changes from false to true exactly once. Binary search finds that change point in O(log n) steps. The copies of target form one block, so both of its edges are change points too.
Can Find First and Last Position of Element in Sorted Array be solved in O(1) extra space?
Yes. The two-search solution keeps only lo, hi, mid and the two answers, which is constant space. The brute force also uses O(1) space, but it takes O(n) time.
Does sorting the array first help?
No. The input is already sorted, and sorting again costs O(n log n) and loses the original indices. Use the existing order with binary search.
Why does the search keep going after it finds target?
One match only proves that target exists. The block of copies can extend left or right, and a plain binary search stops at whichever match it hits first. Narrowing toward the boundary finds the true first or last index.
Asked at
See which companies ask this — Pro
Related problems
- Find K Closest Elements · same technique: Find First/Last Occurrence
- Median of Two Sorted Arrays · next harder, same pattern
- Koko Eating Bananas · same pattern: Binary Search Patterns
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Capacity To Ship Packages Within D Days · same pattern: Binary Search Patterns
- Search in Rotated Sorted Array II · same pattern: Binary Search Patterns
- Find Peak Element · same pattern: Binary Search Patterns
- Peak Index in a Mountain Array · same pattern: Binary Search Patterns