KatInterview

Weekly Trailing Mean Over a Daily Usage Series

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingsliding-windowarraysprefix-sums

Last updated

Compute the mean of every full block of seven consecutive readings in a list, returning an empty list when fewer than seven readings exist; tests sliding-window technique.

A utility company records how much electricity a household uses each day. You are given these daily readings in chronological order and need to summarize them as a series of weekly averages.

Write a function that takes the list of daily readings and returns a list of averages, one for each complete block of 7 consecutive days.

Rules

  • Consider every run of exactly 7 consecutive readings, starting at index 0, then index 1, then index 2, and so on, until the run would go past the end of the list.
  • For each such run, output the arithmetic mean of its 7 readings.
  • The averages must appear in the order of the runs' starting positions (earliest first).
  • Only complete runs of 7 count. If the list has fewer than 7 readings, return an empty list. Do not return partial averages, do not pad the result, and do not raise an error.
  • Do not round the results. Return the plain mean of each run (for example, a sum of 280 over 7 days gives 40.0).
  • A list with n >= 7 readings produces exactly n - 6 averages.

Constraints

  • 0 <= len(readings) <= 10^5
  • Each reading is an integer or a float; values may be zero or negative.
  • The input list must not be modified.
  • Aim for O(n) total time rather than re-summing every run from scratch.

Examples

Example 1

Input: weekly_trailing_mean([10, 20, 30, 40, 50, 60, 70])

Output: [40]

Example 2

Input: weekly_trailing_mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Output: [4, 5, 6, 7]

Example 3

Input: weekly_trailing_mean([5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5])

Output: [8.5, 9.5]

Hints

Hint 1

How many complete 7-day runs does a list of length n contain? Use that to decide what to return when n < 7.

Hint 2

Adjacent runs share six readings. Going from one run to the next, only one reading enters and one leaves.

Hint 3

Keep a running sum: start with the sum of the first 7 readings, then for each new index i add readings[i] and subtract readings[i - 7], dividing by 7 each time.