KatInterview

First Index at Least Target in a Padded Sorted Stream

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchexponential-searchsorted-array

Last 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 is 0 (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

  • readings is sorted in non-decreasing order and contains integers.
  • The length of readings may be 0 and can be very large, so a linear scan is not the intended solution.
  • target is an integer.
  • Return an int: a valid index into readings, 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.