Skip to content

First nonzero entry in an array of unknown size

Question

An array of unknown length consists of a run of zeros followed by nonzero entries. How do you locate the first nonzero entry efficiently?

Short answer

Exponential (galloping) search, then binary search: O(log⁡k)O(\log k) for answer position kk. Probe indices 1,2,4,8,…1,2,4,8,\dots until a nonzero is found at 2m2^m; the first nonzero then lies in (2m−1,2m](2^{m-1},2^m], which binary search pins down in O(m)O(m) further probes. No knowledge of the array length is required.

Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Search algorithm B', p.177; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question