Skip to content

Rolling window average on streaming data

Question

Numbers arrive one at a time. Describe how to maintain the average of the most recent nn values efficiently as each new number arrives.

Short answer

Keep a running sum and a circular buffer of the last nn values. On each arrival add the new value to the sum, subtract the value it overwrites in the buffer, and divide by nn (or by the count so far during warm-up). Each update is O(1)O(1) time with O(n)O(n) memory, versus O(n)O(n) per update if you re-sum the window; periodically recompute the sum to limit floating-point drift.

Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Moving average', p.173; 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