← Infosys bank

Infosys · Question 53 · Queues

Moving Average from Data Stream

QueuesC++code⏱ O(1)💾 O(k)
Service-based

Problem

Design a class to compute moving average of data stream with fixed window size.

Approach

Keep a queue of the last k values and a running sum.

Time O(1)Space O(k)

How it works

  1. 1Keep the last size values with their running sum.
  2. 2Evict the oldest once the window is full.

Sample input / output

Input:
size = 3, stream = [1, 10, 3, 5]
Output:
[1, 5.5, 4.66667, 6]

Constraints

1 <= size <= 1000.

Solution — read it, then walk it

Time O(1)Space O(k)Branches 1Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesnoSTARTinclude <iostream>include <queue>using namespace stdCLASS MovingAveragequeue<int> qDEFINE sizeDEFINE sumDEFINEMovingAverage(int k)DEFINE next(int val)q.push(val)sum += valif ((int)q.size() >size)sum -= q.front()q.pop()RETURN sum / q.size()DEFINE main()MovingAverage m(3)cout << "[" << m.next(1) <<", " << m.next(10) << ", "<< m.next(3) << ", " <…RETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

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