Leftmost Match in a Sorted Sequence Without a Known Size
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Find the first index of a target in a sorted list while the search pretends its length is unknown, using doubling probes followed by a lower-bound binary search.
You are given a list values of integers sorted in non-decreasing order, and an integer target.
Imagine you were only allowed to read the list one position at a time, and reading past the final position yields a "too large" sentinel (as if the value were positive infinity). Under that mindset you would not know the list's size ahead of time, so you cannot simply binary search over [0, len - 1] from the start. Design your algorithm in that spirit: first discover a range that must contain the answer, then search inside it.
Return the smallest index i such that values[i] == target. If the target does not occur in the list, return -1.
Details:
- The list may contain repeated values. When the target appears several times, return the position of its first (leftmost) appearance.
- The list may be empty, in which case the answer is
-1. - The target may be smaller than every element, larger than every element, or fall between two neighbouring elements; in each of these cases where it is not present, return
-1.
Aim for a running time of O(log p), where p is the index of the first element that is greater than or equal to target (or the list length if there is none), using O(1) extra space. A linear scan, or measuring the length by walking the list, is not the intended solution.
Constraints
0 <= len(values) <= 10^6valuesis sorted in non-decreasing order.- Each element and
targetfit in a 32-bit signed integer. - Return an integer: the leftmost index of
target, or-1if it is absent.
Examples
Example 1
Input: find_first_occurrence_unbounded([1, 3, 5, 7, 9], 7)
Output: 3
Example 2
Input: find_first_occurrence_unbounded([1, 3, 5, 7, 9], 4)
Output: -1
Example 3
Input: find_first_occurrence_unbounded([1, 2, 2, 2, 4, 8], 2)
Output: 1
Example 4
Input: find_first_occurrence_unbounded([10, 20, 30], 5)
Output: -1
Hints
Hint 1
Without a known length, start with a small window and grow it. Probe positions 1, 2, 4, 8, ... until you reach a value that is at least the target or you step past the end.
Hint 2
Once the doubling stops, the first position holding a value >= target must lie between the previous probe and the current one (clamped to the last valid index). Binary search only that window.
Hint 3
Do not return as soon as you see the target in the binary search. Move the right end to mid when values[mid] >= target so you converge on the leftmost candidate, then verify it equals the target.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since the length is treated as unknown, we cannot start with a standard binary search. The solution has two phases.
-
Quick exits. If the list is empty, or
values[0] > target, the answer is-1. Ifvalues[0] == target, the answer is0. After this, we knowvalues[0] < target. -
Doubling phase. Set
bound = 1and keep doubling it whileboundis still a valid index andvalues[bound] < target. Reading past the end plays the role of the "too large" sentinel, so the loop stops there as well. When it stops, eitherboundis out of range orvalues[bound] >= target. -
Binary search phase. The first position holding a value
>= targetlies in(bound // 2, bound], becausevalues[bound // 2] < target(it was either index 0, which we checked, or an earlier doubling probe that passed the< targettest). Clamp the right end ton - 1. Run a lower-bound search on[bound // 2, min(bound, n - 1)]: ifvalues[mid] < target, setlo = mid + 1; otherwise sethi = mid. We never stop early on equality, so we converge to the leftmost candidate. -
Verification. Return
loifvalues[lo] == target, otherwise-1.
Why it is correct
The window invariant guarantees the leftmost element >= target is inside the searched range. The lower-bound search finds the leftmost index in that range with value >= target (or the last index if none qualifies). If that value equals target, no earlier index can hold target, since everything before is < target, so it is the first occurrence. If not, the target is absent. Duplicates are handled because we never terminate on a match; we keep shrinking toward the left.
Complexity
Let p be the index of the first element >= target (or n if none).
- Time: the doubling phase takes
O(log p)probes, and the window it produces has size at most aboutp, so the binary search also takesO(log p). TotalO(log p), at mostO(log n). - Space:
O(1).
Reference solution
from typing import List
def find_first_occurrence_unbounded(values: List[int], target: int) -> int:
n = len(values)
if n == 0:
return -1
if values[0] > target:
return -1
if values[0] == target:
return 0
# Phase 1: doubling to find an upper bound.
bound = 1
while bound < n and values[bound] < target:
bound *= 2
# Phase 2: lower-bound binary search in [bound // 2, min(bound, n - 1)].
lo = bound // 2
hi = min(bound, n - 1)
while lo < hi:
mid = (lo + hi) // 2
if values[mid] < target:
lo = mid + 1
else:
hi = mid
return lo if values[lo] == target else -1