Calculate 7-Day Rolling Average for Energy Consumption
Company: Amazon
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
##### Scenario
Hiring manager wants a quick coding exercise to verify programming fluency.
##### Question
Write a Python function that takes a list of daily energy consumption values and returns a list containing the 7-day rolling average; handle cases with fewer than 7 observations.
##### Hints
Use sliding window or collections.deque; O(n) time.
Quick Answer: This question evaluates programming fluency in numerical data processing and algorithmic implementation for computing moving averages and handling edge cases in time-series sequences, and it applies to Data Scientist roles while falling under the Coding & Algorithms category.
Given a list of daily energy consumption values (non-negative numbers), return a list of the same length where each element i is the average of the last up to 7 values ending at position i. For the first few days with fewer than 7 observations, use all available observations so far. Return each average rounded to two decimal places. If the input list is empty, return an empty list.
Constraints
- 0 <= len(consumption) <= 200000
- 0 <= consumption[i] <= 1e9
- Output list length equals input list length
- Each average is computed over the last up to 7 elements ending at that index
- Round each average to two decimal places
- Time complexity O(n); extra space O(1) aside from output
Hints
- Maintain a running sum of the current window and update it in O(1) per step.
- When the window size exceeds 7, subtract the element that falls out from the left.
- Use round(value, 2) to round each average to two decimal places.