Steady State
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
- Asked in
- Gemini
Problem
Return the mean of every run of k consecutive samples in nums, each rounded to two decimals, as the smoothed series a metrics dashboard plots in sample order. When the buffer holds fewer than k samples there is nothing to smooth, so return an empty list.
Turn a jittery stream into a calm read, one step at a time.
Example 1
Input:
nums = [1,2,3,4,5], k = 3
Output:
[2,3,4]
Example 2
Input:
nums = [1,2,2], k = 3
Output:
[1.67]
Worked solution and explanation
What this really is
Strip the dashboard costume and this is a fixed-size sliding window. The windows overlap and advance one sample at a time, so [1, 2, 3, 4, 5] with k = 3 gives three means, not one. Candidates who chop the list into blocks of k return [2.0] and quietly drop the tail. Once the overlap is clear, the second tell is carrying a running sum instead of re-summing k numbers per window. Miss that and a long stream with a wide window turns O(n) into O(n * k).
The trap most people walk into
The short-buffer rule is load-bearing. Jump straight into summing the first k elements and a short input either throws or divides a partial sum by k, returning a wrong value instead of an empty list. Check the length before you touch nums[k - 1]. The rounding is part of the answer too: [1, 2, 2] must come back as 1.67, not 1.6666666666666667.
Step 1: Handle the short-input case first
If len(nums) < k, return [] immediately. This both satisfies the spec and protects the first-window sum from an index error.
Step 2: Seed the running sum
Sum the first k elements once. This is the only full summation you ever do.
Step 3: Slide one element at a time
For each later position, add the entering element and subtract the one that fell out of the window, then store the rounded mean. The sum updates in O(1).
The solution
def moving_average(nums, k):
if len(nums) < k:
return []
result = []
window_sum = sum(nums[:k])
result.append(round(window_sum / k, 2))
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k]
result.append(round(window_sum / k, 2))
return resultSeed once, then adjust by the entering and leaving element per step.
Common follow-up questions
- What if the dashboard wanted the moving median instead of the mean? (Tests a sorted container or two-heap approach for O(k log k) per window.)
- How would you compute this on a never-ending streaming input? (Tests a fixed-size deque buffer instead of random access into a list.)
- Does anything change if samples can be negative or non-integer? (Tests handling negative or fractional samples and confirming the rounding still holds.)