Quant Memo
Coding/●●●●●

Moving average from a stream

Ticks arrive one at a time from a market-data feed. Design a class that, after each new tick, returns the average of the last k prices seen (or of all prices, if fewer than k have arrived).

m = MovingAverage(k=3)
m.update(10)  -> 10.0
m.update(20)  -> 15.0
m.update(30)  -> 20.0
m.update(40)  -> 30.0      # window is now [20, 30, 40]

Each update must run in O(1)O(1) time and the class must use O(k)O(k) memory.

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions