Find First and Last Position in a Sorted Array
Given an array of integers nums sorted in non-decreasing order and a value target, return the index of the first and last occurrence of target as [first, last]. If target isn't in the array, return [-1, -1].
Your solution must run in O(log n) time.
Example 1
Input: nums = [5, 7, 7, 8, 8, 10], target = 8 Output: [3, 4]
8 first appears at index 3 and last appears at index 4.
Example 2
Input: nums = [5, 7, 7, 8, 8, 10], target = 6 Output: [-1, -1]
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i], target <= 10^9numsis sorted in non-decreasing order.
Approach
A linear scan finds both ends in O(n). A plain binary search finds one copy of target in O(log n), but expanding outward from it is O(n) again when most of the array is target.
Search for boundaries instead. Write one helper, first_at_least(value), that returns the first index whose element is >= value. When nums[mid] < value, the boundary is to the right of mid. Otherwise mid might be the boundary, so keep it in range and look left. The loop ends when the range closes on a single index.
The first occurrence of target is first_at_least(target), as long as that index is in bounds and actually holds target. The last occurrence is one before first_at_least(target + 1).
Steps
- Write a binary search that returns the first index with a value
>= value, or the array's length if there's none. - Set
start = first_at_least(target). - If
startis out of bounds ornums[start] != target, return[-1, -1]. - Set
end = first_at_least(target + 1) - 1and return[start, end].
from typing import List
def search_range(nums: List[int], target: int) -> List[int]:
def first_at_least(value):
# Index of the first element >= value, or len(nums) if there is none.
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < value:
lo = mid + 1
else:
hi = mid
return lo
start = first_at_least(target)
if start == len(nums) or nums[start] != target:
return [-1, -1]
end = first_at_least(target + 1) - 1 # last element < target + 1
return [start, end]Complexity
- Time:
O(log n). Two binary searches. - Space:
O(1).
Common mistakes
- Stopping the search as soon as
nums[mid] == target, which finds an arbitrary copy rather than the first. - Forgetting the empty array and the case where
targetis larger than every element, both of which return an index equal to the length. - Computing
target + 1as a 32-bit int. It's safe within these constraints, but it overflows iftargetis the largest int, so the Java and C++ solutions widen it first.
class Solution: def countFreq(self, arr, target): n = len(arr) left = 0 right = n - 1 first = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: first = mid right = mid - 1 elif arr[mid] < target: left = mid + 1 else: right = mid - 1 left = 0 right = n - 1 last = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: last = mid left = mid + 1 elif arr[mid] < target: left = mid + 1 else: right = mid - 1 if first == -1: return 0 return last - first + 1