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
A monitoring service buffers raw metric samples in nums, and the dashboard smooths the jitter by reporting the mean of each run of k consecutive samples, each value rounded to two decimals. Return one average per window, in sample order. When there are 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:
k = 3, nums = [1,2,3,4,5]
Output:
[2,3,4]
Example 2
Input:
k = 3, nums = [1,2,2]
Output:
[1.67]
Worked solution and explanation
What this really is
Strip the time-series costume and this is a running-sum problem. The skill being probed is whether you can compute every window's mean in one pass instead of re-summing k numbers per window. Anyone can nest two loops; the tell is whether you carry a running sum and only adjust it by the one element that leaves and the one that enters. Miss that and a long stream with a wide window turns an O(n) task into O(n * k).
The trap most people walk into
The prompt says return an empty list when there are fewer than k samples, and that clause is load-bearing. If you jump straight into summing the first k elements without checking the length first, a short input indexes past the end of the list and throws instead of returning []. Guard the length before you touch nums[k-1].
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.)