First Index at Least Target in a Padded Sorted Stream
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Find the first index with value at least the target in a sorted sequence of hidden length, using doubling probes followed by binary search.
First Index at Least Target in a Padded Sorted Stream
A sorted sequence of integers is exposed through a read-only probe probe(i), and its length is not known. Probing any index i at or past the end returns positive infinity, so you can think of the data as the stored values followed by infinitely many +∞ entries.
In this exercise the data is passed to you as a Python list readings. Treat it as if only the probe were available. Never call len to decide where to search, and instead write the probe as readings[i] if i is inside the list and float('inf') otherwise. A good solution needs only O(log n) probes.
Task
Given the non-decreasing list readings and an integer target, return the smallest index i such that readings[i] >= target.
If no stored value is at least target, return -1.
Rules and edge cases
- The values are in non-decreasing order, and duplicates are allowed. When several entries qualify, return the leftmost one.
- An empty list has no qualifying entry, so the answer is
-1. - If every value is at least
target, the answer is0(for a non-empty list). - If every value is strictly less than
target, the answer is-1. - The
+∞padding never counts as a real answer. An index at or beyond the end of the list is never returned.
Constraints
readingsis sorted in non-decreasing order and contains integers.- The length of
readingsmay be0and can be very large, so a linear scan is not the intended solution. targetis an integer.- Return an
int: a valid index intoreadings, or-1. - Aim for O(log n) time and O(1) extra space.
Examples
Example 1
Input: first_at_least_unbounded([], 5)
Output: -1
Example 2
Input: first_at_least_unbounded([1, 3, 5, 7], 4)
Output: 2
Example 3
Input: first_at_least_unbounded([1, 2, 2, 2, 6], 2)
Output: 1
Hints
Hint 1
Imagine the list continued forever with +infinity. The test 'value >= target' is then false for a prefix and true from some point onward, and that point is what you are looking for.
Hint 2
Without knowing n, grow a probe index by doubling (1, 2, 4, 8, ...) until the probed value is at least target. This brackets the answer between the last failing probe and the first succeeding one.
Hint 3
Binary search inside the bracket while keeping the invariant 'value at lo < target <= value at hi'. At the end, hi is the first index that passes; if it lies beyond the real data, return -1. Handle index 0 separately first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Extend the list conceptually with infinitely many +∞ values. The extended sequence is still non-decreasing, so the predicate value >= target is monotone: false for a prefix, then true forever. The answer is the first index where it turns true. If that index falls inside the +∞ padding, no real element qualifies and we return -1.
The algorithm has three steps.
- Check index 0. If
probe(0) >= target, then the answer is0for a non-empty list. For an empty list, the value at 0 is padding, so return-1. - Gallop. Start with
lo = 0,hi = 1. Whileprobe(hi) < target, setlo = hiand doublehi. Everyloassigned here has a value belowtarget, and the loop must stop because the padding is infinite andtargetis finite. - Binary search the bracket. While
lo + 1 < hi, testmid = (lo + hi) // 2. Ifprobe(mid) >= target, sethi = mid, otherwise setlo = mid. Finally, returnhiif it is a real index, else-1.
Why it is correct
After step 1, the invariant probe(lo) < target <= probe(hi) holds. It is true at the end of galloping by construction, and each binary-search step keeps it true while strictly shrinking the gap. When the loop ends, hi = lo + 1, so hi is the first index whose value is at least target, because lo fails and the sequence is monotone. Duplicates are handled automatically: an index equal to target is moved onto hi, and the search keeps looking left of it, so the leftmost qualifying index is found. If hi is at or past the list length, every real element was below target, so -1 is correct.
Complexity
Let p be the answer index (or n if none). Galloping uses about ⌈log₂ p⌉ + 1 probes, and the binary phase searches a bracket of size at most p, using about ⌈log₂ p⌉ - 1 probes. In total this is roughly 2⌈log₂ n⌉ + 1 probes in the worst case.
- Time: O(log n)
- Space: O(1)
Reference solution
from typing import List
def first_at_least_unbounded(readings: List[int], target: int) -> int:
def probe(i):
# Simulated black-box access: +infinity beyond the end.
return readings[i] if i < len(readings) else float('inf')
# Index 0 is either the answer or the padding (empty list).
if probe(0) >= target:
return 0 if readings else -1
# Phase 1: gallop. Invariant: probe(lo) < target.
lo, hi = 0, 1
while probe(hi) < target:
lo = hi
hi *= 2
# Phase 2: binary search. Invariant: probe(lo) < target <= probe(hi).
while lo + 1 < hi:
mid = (lo + hi) // 2
if probe(mid) >= target:
hi = mid
else:
lo = mid
# hi is the first passing index; reject the infinite padding.
return hi if hi < len(readings) else -1