Skip to content
BytePatterns

Search a List of Unknown Length

MediumSearching#binary-search#exponential-search~25m

Problem

A sorted list of numbers, smallest first and possibly with repeats, is hidden behind a reader. The only way to look at it is reader.get(i), which returns the value at index i, or None once i is past the end; the length is never given. Return the first index that holds the target, or -1 if the target is absent, using a number of reads that grows only with the logarithm of that index.

Examples

Input:  values = [2, 5, 5, 9, 14, 20, 31], target = 9
Output: 3
Why:    9 sits at index 3
Input:  values = [2, 5, 5, 9, 14, 20, 31], target = 5
Output: 1
Why:    5 appears twice, and the first copy is at index 1
Input:  values = [], target = 1
Output: -1
Why:    edge case, the very first read already returns None

Hints

0 / 3

Stuck on the idea rather than the code? O(log n) and Halving covers it.