← Google bank

Google · Question 49 · Queues

Moving Average from Data Stream

QueuesPythoncode⏱ O(1)💾 O(size)
Product-based

Problem

Calculate moving average from a stream of integers given a window size.

Approach

Use a queue to store window elements and a running sum.

Time O(1)Space O(size)

How it works

  1. 1Keep the last size values in a queue with their running sum.
  2. 2Evict the oldest value once the window is full.
  3. 3Add the new value and return sum over window size.

Sample input / output

Input:
3 4
1 10 3 5
Output:
[1.0, 5.5, 4.666666666666667, 6.0]

Constraints

1 <= size <= 1000; -10^5 <= val <= 10^5; at most 10^4 calls to next.

Solution — read it, then walk it

Time O(1)Space O(size)Branches 2Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoSTARTfrom collections importdequeCLASS MovingAverageDEFINE __init__(self, size)self.size = sizeself.queue = deque()self.window_sum = 0DEFINE next(self, val)if len(self.queue) ==self.sizeself.window_sum -=self.queue.popleft()self.queue.append(val)self.window_sum += valRETURN self.window_sum /len(self.queue)DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)size = int(next(it)); n =int(next(it))m = MovingAverage(size)out =[m.next(int(next(it))) for_ in range(n)]print(out)if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits