NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

How can you perform binary search on a sorted array of infinite or unknown length (when the count function is unavailable)?

Practice

AI answer

Use exponential search to find the bounds, then run a standard binary search within them. Start at index 0 and double the index (1, 2, 4, 8, ...) while the value there is less than the target. This finds an interval containing the target. Then perform a binary search within that interval.

If the array is actually finite but its length is unknown, an access beyond its bounds must be recognized as the end of the data—for example, as a special read result. Without a way to determine that an index is invalid or to check the value at an index, the problem cannot be solved.

The complexity is O(log i), where i is the position of the target element; the extra space is O(1). To find the first occurrence when there are duplicates, continue the binary search to the left after finding a match.