Full answer
Problem
Given sorted integers nums and target, return [first, last] indices of target, or [-1, -1].
Example: [5, 7, 7, 8, 8, 10], target 8 gives [3, 4]; target 6 gives [-1, -1].
Constraints: 0 <= len(nums) <= 10^5, sorted non-decreasing. Must be O(log n).
Brute force
Scan for the first and last match: O(n). Or binary search for any match and walk outwards, which is O(n) when the whole list is the target.
Optimal approach
Lower bound with a half-open range [lo, hi):
lo = 0,hi = len(nums).- While
lo < hi:mid = (lo + hi) // 2; ifnums[mid] < target,lo = mid + 1, elsehi = mid. - Return
lo.
Then:
first = lower_bound(target); iffirst == len(nums)ornums[first] != target, return[-1, -1].last = lower_bound(target + 1) - 1.
Why it works
Lower bound searches for the boundary of the predicate nums[i] >= target, which is false then true across a sorted list. The loop keeps "everything before lo is false" and "everything from hi onwards is true", and stops when they meet at the first true position. For integers, the first index with value at least target + 1 is one past the last target.
This is what bisect.bisect_left and bisect.bisect_right compute; the test checks the hand-written version against bisect.
Complexity
Two binary searches: O(log n) time, O(1) space.
Code
def lower_bound(nums, target):
"""First index i with nums[i] >= target (len(nums) if none)."""
lo, hi = 0, len(nums) # search in the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def search_range(nums, target):
"""[first, last] index of target in sorted nums, or [-1, -1]. O(log n)."""
first = lower_bound(nums, target)
if first == len(nums) or nums[first] != target:
return [-1, -1]
last = lower_bound(nums, target + 1) - 1 # integers: first value > target
return [first, last]
if __name__ == "__main__":
import bisect
assert search_range([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert search_range([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert search_range([], 0) == [-1, -1]
assert search_range([2, 2, 2], 2) == [0, 2]
assert search_range([1], 1) == [0, 0]
data = [1, 3, 3, 3, 9]
for x in range(0, 11):
assert lower_bound(data, x) == bisect.bisect_left(data, x)
print("all tests passed")Save as a28_first_last.py and run python3 a28_first_last.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list. Target absent but between values, below all, or above all. All elements equal to the target ([0, n - 1]). A single element. For non-integer keys, replace target + 1 with an upper bound search using <= in the comparison.
Pattern
Binary search for a boundary (first true of a monotonic predicate). It is the base for counting occurrences, insert position, and binary search on the answer.
def lower_bound(nums, target):
"""First index i with nums[i] >= target (len(nums) if none)."""
lo, hi = 0, len(nums) # search in the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def search_range(nums, target):
"""[first, last] index of target in sorted nums, or [-1, -1]. O(log n)."""
first = lower_bound(nums, target)
if first == len(nums) or nums[first] != target:
return [-1, -1]
last = lower_bound(nums, target + 1) - 1 # integers: first value > target
return [first, last]
if __name__ == "__main__":
import bisect
assert search_range([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert search_range([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert search_range([], 0) == [-1, -1]
assert search_range([2, 2, 2], 2) == [0, 2]
assert search_range([1], 1) == [0, 0]
data = [1, 3, 3, 3, 9]
for x in range(0, 11):
assert lower_bound(data, x) == bisect.bisect_left(data, x)
print("all tests passed")A half-open lower_bound used twice; the test compares it with bisect.bisect_left on every value.
Complexity
Time: O(log n). Space: O(1). Walking outward from one match would be O(n) in the worst case.
By level
Fresher: Writes two binary searches, one biased left and one biased right, and tests duplicates and an absent target. Should test a list made entirely of the target.
Mid: Expresses it as lower and upper bound with a clear predicate and compares with bisect. Explains the half-open range convention.
Senior: Generalises boundary search to arbitrary monotonic predicates and non-integer keys, and discusses API design for range queries on sorted data. Can explain how the boundary search works on non-integer keys.
Key points
- Lower bound finds the first index with value >= target
- Half-open range [lo, hi) with hi = mid avoids skipping the answer
- Last position = lower_bound(target + 1) - 1 for integers
- bisect_left and bisect_right are the library versions
- Both searches are O(log n)
Common mistakes
- Walking outward from a match
- Mixing closed and half-open conventions in one loop
- Not checking that nums[first] is the target
- Using target + 1 for floats or strings
Follow-ups
- How many times does the target occur?
- How would you find the insert position for a new value?
- How do you write upper bound directly?
Tips
- Frame it as "first true of a predicate"
- Show the library equivalent
- Test a list made entirely of the target
Evaluation rubric
- Correct boundary searches
- Correct handling of absent target
- O(log n) overall
- Consistent loop convention