Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an array nums sorted in non-decreasing order, so repeats are allowed, and a target. Return [first, last]: the first and last index where target appears. If it doesn't appear, return [-1, -1]. Your solution must run in O(log n) time. The array can be empty and has up to 10⁵ elements.
Example: nums = [5, 7, 7, 8, 8, 10], target = 8 → [3, 4]. With target = 6, the answer is [-1, -1].
Start with brute force
Scan from the left for the first copy, and from the right for the last copy. That's O(n).
A tempting "fix" is to binary search for any copy, then walk outwards while the neighbours are equal. That's O(log n) to find one copy, but if the array is 10⁵ copies of the same number, the walk is 10⁵ steps. Still O(n) in the worst case.
Building the intuition
Don't search for "a copy". Search for a boundary. Write the two yes/no questions from the primer under the example, with target = 8:
| i | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| nums[i] | 5 | 7 | 7 | 8 | 8 | 10 |
| nums[i] >= 8? | F | F | F | T | T | T |
| nums[i] > 8? | F | F | F | F | F | T |
Both rows are falses-then-trues, so binary search can find the first T in each.
- The first T of
>= 8is index 3, the first copy. That's the lower bound. - The first T of
> 8is index 5, the first number past all the 8s. That's the upper bound. The last copy is one before it: index 4.
So the whole problem is two runs of the same template, changing >= to >. That's it. And if the target is missing, the lower bound lands on something that isn't the target (or past the end), which you can check.
The optimal approach
- Lower bound.
lo = 0,hi = n. Whilelo < hi:mid = lo + (hi - lo) // 2; ifnums[mid] >= target,hi = mid, elselo = mid + 1. Call the resultfirst. - Missing? If
first == nornums[first] != target, return[-1, -1]. - Upper bound. Same loop from
lo = 0,hi = n, but withnums[mid] > target. Call the resultupper. - Return
[first, upper - 1].
The subtle detail: the upper bound is one past the last copy. It's the first index that is strictly bigger, so you must subtract 1. Forgetting the - 1 is the most common bug here. Also, the second search can't land on n "by accident" and break anything: upper = n just means the copies run to the end of the array, so upper - 1 = n - 1 is correct.
Some people do the second search with >= target + 1. For integers that's the same question, but target + 1 can overflow when target is the largest int. Writing > avoids that.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
# Lower bound: first index with nums[i] >= target, i.e. the first copy.
lo, hi = 0, n
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] >= target:
hi = mid
else:
lo = mid + 1
first = lo
# Landing past the end, or on a bigger number, means target is missing
if first == n or nums[first] != target:
return [-1, -1]
# Upper bound: first index with nums[i] > target, i.e. one PAST the last copy.
lo, hi = 0, n
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] > target: # the only change: > instead of >=
hi = mid
else:
lo = mid + 1
upper = lo
return [first, upper - 1]class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
// Lower bound: first index with nums[i] >= target, i.e. the first copy.
int lo = 0, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] >= target) {
hi = mid;
} else {
lo = mid + 1;
}
}
int first = lo;
// Landing past the end, or on a bigger number, means target is missing
if (first == n || nums[first] != target) return {-1, -1};
// Upper bound: first index with nums[i] > target, i.e. one PAST the last copy.
lo = 0, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > target) { // the only change: > instead of >=
hi = mid;
} else {
lo = mid + 1;
}
}
int upper = lo;
return {first, upper - 1};
}
};class Solution {
public int[] searchRange(int[] nums, int target) {
int n = nums.length;
// Lower bound: first index with nums[i] >= target, i.e. the first copy.
int lo = 0, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] >= target) {
hi = mid;
} else {
lo = mid + 1;
}
}
int first = lo;
// Landing past the end, or on a bigger number, means target is missing
if (first == n || nums[first] != target) return new int[] { -1, -1 };
// Upper bound: first index with nums[i] > target, i.e. one PAST the last copy.
lo = 0;
hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > target) { // the only change: > instead of >=
hi = mid;
} else {
lo = mid + 1;
}
}
int upper = lo;
return new int[] { first, upper - 1 };
}
}/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
const n = nums.length;
// Lower bound: first index with nums[i] >= target, i.e. the first copy.
let lo = 0, hi = n;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] >= target) {
hi = mid;
} else {
lo = mid + 1;
}
}
const first = lo;
// Landing past the end, or on a bigger number, means target is missing
if (first === n || nums[first] !== target) return [-1, -1];
// Upper bound: first index with nums[i] > target, i.e. one PAST the last copy.
lo = 0;
hi = n;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] > target) { // the only change: > instead of >=
hi = mid;
} else {
lo = mid + 1;
}
}
const upper = lo;
return [first, upper - 1];
};Dry run
nums = [5, 7, 7, 8, 8, 10], target = 8, n = 6.
Lower bound (nums[mid] >= 8?):
| lo | mid | hi | nums[mid] | >= 8? | update |
|---|---|---|---|---|---|
| 0 | 3 | 6 | 8 | Yes | hi = 3 |
| 0 | 1 | 3 | 7 | No | lo = 2 |
| 2 | 2 | 3 | 7 | No | lo = 3 |
| 3 | 3 | first = 3 |
nums[3] = 8, so the target is present.
Upper bound (nums[mid] > 8?):
| lo | mid | hi | nums[mid] | > 8? | update |
|---|---|---|---|---|---|
| 0 | 3 | 6 | 8 | No | lo = 4 |
| 4 | 5 | 6 | 10 | Yes | hi = 5 |
| 4 | 4 | 5 | 8 | No | lo = 5 |
| 5 | 5 | upper = 5 |
Return [3, 5 - 1] = [3, 4].
Look at the first row of each table. mid = 3 holds an 8 both times. The lower bound treats it as "yes, keep looking left", while the upper bound treats it as "no, keep looking right". That one-character difference is what steers each search to its own end of the run of 8s.
Complexity
- Time: O(log n). Two binary searches of about log₂ n steps each, 17 apiece for 10⁵ elements, no matter how many copies there are.
- Space: O(1). A few integers.
Edge cases and traps
- Empty array.
n = 0, so the first loop doesn't run andfirst = 0 = n. The missing check returns[-1, -1], and you never readnums[0]. - Forgetting
upper - 1. Returns[3, 5]for the example. The upper bound is past the last copy. - Target smaller or bigger than everything. The lower bound lands on 0 or
n, and the missing check catches both. - Every element is the target.
first = 0andupper = n, so you return[0, n - 1]. The "find one, then walk" approach would take O(n) here. - Reading
nums[first]without checkingfirst < n. Crashes when the target is bigger than every element.
Say it in the interview
"I don't look for a copy of the target. I look for the two boundaries. The first copy is the lower bound: the first index where nums[i] is at least the target. One past the last copy is the upper bound: the first index where nums[i] is strictly greater. Both questions are false then true, so each is one binary search with the same loop, only the comparison changes. If the lower bound doesn't hold the target, I return minus one, minus one. Otherwise it's lower bound and upper bound minus one. O(log n) time, O(1) space."
Follow-ups interviewers ask
- "How many times does the target appear?"
upper - first. Still O(log n), even if the answer is 10⁵. - "Can you skip part of the second search?" Yes: start it at
lo = first, since everything beforefirstis smaller than the target. Same big-O. - "Find the number of elements in a range [a, b]." Upper bound of
bminus lower bound ofa. You used the same idea in Interesting Drink, where the upper bound is the count of prices<= m.
Practise the same idea
This is Day 42 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free