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: for answer position . Probe indices until a nonzero is found at ; the first nonzero then lies in , which binary search pins down in 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