Locate the Span of a Value in a Sorted List
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Use binary search to find the first and last positions of a value in a sorted list with duplicates, in logarithmic time, returning [-1, -1] if it is absent.
Locate the Span of a Value in a Sorted List
You are given a list of integers values sorted in non-decreasing order (duplicates are allowed) and an integer key.
Because the list is sorted, all occurrences of key form one contiguous block. Return the zero-based index where this block begins and the zero-based index where it ends (both inclusive), as a list [start, end].
If key does not occur in values, return [-1, -1].
Your solution must run in O(log n) time, where n is the length of the list. A linear scan, or finding one match and then expanding outward, does not meet this requirement.
Input
values: a list of integers sorted in non-decreasing order. It may be empty.key: an integer to search for.
Output
- A list of two integers
[start, end], the first and last index at whichkeyappears. [-1, -1]ifkeyis not present.- If
keyappears exactly once,startandendare equal.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i] <= 10^9valuesis sorted in non-decreasing order.-10^9 <= key <= 10^9
Edge cases to handle
- An empty list.
- Every element equals
key. keyis smaller than every element or larger than every element.keylies between two existing values but is not itself present.
Examples
Example 1
Input: find_value_span([5, 7, 7, 8, 8, 10], 8)
Output: [3, 4]
Example 2
Input: find_value_span([5, 7, 7, 8, 8, 10], 6)
Output: [-1, -1]
Example 3
Input: find_value_span([], 0)
Output: [-1, -1]
Hints
Hint 1
Sorted order means all copies of the key are adjacent, so you only need to find the two boundaries of that block.
Hint 2
Write a binary search that returns the first index whose element is >= key. A second search for the first index whose element is > key gives the position just past the block.
Hint 3
After the first search, check that the index is inside the list and that the element there really equals the key. Do this check before reading the element so an empty list does not cause an error.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
All copies of key sit in one contiguous block, so it is enough to locate the two ends of that block. Each end can be found with a binary search.
Define two insertion points:
- Lower bound: the first index
iwherevalues[i] >= key. If the key exists, this is its first occurrence. - Upper bound: the first index
iwherevalues[i] > key. The index just before it,upper - 1, is the last occurrence.
Steps:
- Compute
start = lower_bound(key). - If
start == len(values)orvalues[start] != key, the key is absent, so return[-1, -1]. - Otherwise compute
end = upper_bound(key) - 1and return[start, end].
Avoid the tempting approach of finding any match and then walking outward. When every element equals key, that walk takes O(n) time.
Why it is correct
Each bound is a search for the first index where a monotone predicate becomes true. In a sorted list, values[i] >= key looks like False ... False True ... True, and values[i] > key has the same shape. The binary search keeps a half-open window [lo, hi) such that every index below lo fails the predicate and every index at or above hi satisfies it. If the predicate holds at mid, set hi = mid; otherwise set lo = mid + 1. The window shrinks each step, and when lo == hi that index is the first position where the predicate holds (possibly len(values)).
The existence check is valid because, if the key is present, the first element that is >= key must equal key. If it is absent, that element is either larger than key or does not exist. When the check passes, the range [start, upper - 1] is non-empty and contains exactly the copies of key.
Complexity
- Time:
O(log n), from at most two binary searches. - Space:
O(1)extra.
Reference solution
from bisect import bisect_left, bisect_right
from typing import List
def find_value_span(values: List[int], key: int) -> List[int]:
start = bisect_left(values, key)
if start == len(values) or values[start] != key:
return [-1, -1]
end = bisect_right(values, key) - 1
return [start, end]
bisect_left is the lower bound and bisect_right is the upper bound. The explicit existence check is still required, because they return insertion points rather than a found flag.