Locate the Span of a Value in a Sorted List
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Use binary search to find the first and last positions of a value in a sorted list in logarithmic time, returning [-1, -1] when it is absent.
You are given a list of integers values arranged in non-decreasing order, together with an integer needle.
Determine the zero-based position of the earliest element equal to needle and the position of the latest element equal to needle. Return them as a two-element list [first, last].
If needle does not occur anywhere in values, return [-1, -1]. If it occurs exactly once, both entries are the same index.
Requirements
- The solution must run in O(log n) time, where
nis the length ofvalues. Scanning the list linearly, or finding one match and walking outward, is too slow when many elements are equal.
Input
values: a list of integers sorted in non-decreasing order (it may be empty).needle: an integer.
Output
- A list of two integers
[first, last], or[-1, -1]ifneedleis not present.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i], needle <= 10^9valuesis sorted in non-decreasing order (duplicates are allowed).
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
All copies of the needle form one contiguous block, so you only need the two ends of that block rather than every match.
Hint 2
Binary search can find the first index whose value is at least the needle. A second, similar search finds the first index whose value is strictly greater than the needle.
Hint 3
After the first search, check that the index is inside the list and that the value there equals the needle before trusting it; otherwise the answer is [-1, -1]. The last position is one before the second search's result.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because the list is sorted, every element equal to needle sits in one contiguous block. The task is therefore to find the two boundaries of that block, and each boundary can be located with its own binary search.
- Lower boundary: the first index
iwithvalues[i] >= needle. - Upper boundary: the first index
iwithvalues[i] > needle.
If the needle is present, the block spans from the lower boundary up to one position before the upper boundary.
Steps:
- Run the lower-boundary search to get
first. - If
firstequalslen(values)(every element is smaller) orvalues[first] != needle(the value at that spot is larger), the needle is absent, so return[-1, -1]. The length check must come before readingvalues[first]to avoid an index error. - Otherwise run the upper-boundary search and subtract one to get
last. Return[first, last].
Why it is correct
The condition values[i] >= needle is false for a prefix of indices and true for the rest, because the list is non-decreasing. Binary search finds the point where it flips, and returns len(values) if it never does. Everything before first is strictly smaller than the needle, so if values[first] == needle, it is the earliest occurrence. Likewise values[i] > needle flips from false to true exactly once, so every index before the upper boundary holds a value at most needle. Combined with the lower bound, the indices from first to upper - 1 hold exactly the needle, so upper - 1 is the last occurrence.
Complexity
- Time: O(log n), since at most two binary searches are performed.
- Space: O(1).
Reference solution
from bisect import bisect_left, bisect_right
from typing import List
def find_value_span(values: List[int], needle: int) -> List[int]:
first = bisect_left(values, needle)
if first == len(values) or values[first] != needle:
return [-1, -1]
return [first, bisect_right(values, needle) - 1]