Rolling window totals over filtered records in input order
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests filtering a list of tagged records and computing rolling window totals in O(n) using an incremental sum instead of recomputing each window.
You are given a list of records. Each record is a dictionary with three keys:
"tags": a list of strings,"timestamp": an integer (informational only; it does not affect ordering),"value": a number (int or float).
Write a function that takes the records, a tag string tag, and a window size k. First, keep only the records whose "tags" list contains tag exactly, preserving their original order in the input list. Then return the sum of "value" over every window of k consecutive kept records. Window i covers kept records i through i + k - 1, so the result is ordered from the first window to the last.
Do not sort the records. Their order in the input is the order that defines "consecutive."
Constraints:
- If
k <= 0, return an empty list. - If fewer than
krecords match, return an empty list. - If no records match, return an empty list.
- Tag matching is exact string equality. For example,
"env:prod"does not match"env:prod-eu". - A record whose tags list contains the same tag more than once still counts as one matching record.
- Values may be negative, zero, or floats. No ordering or monotonicity is assumed.
- The number of records is up to 2 * 10^5. Each record has at most 20 tags.
- Each value fits in a 64-bit signed integer range when integers are used.
- Aim for O(n) time over the records, where each window sum after the first is derived from the previous one in O(1).
Examples
Example 1
Input: rolling_tag_window_sums([{'tags': ['host:web', 'env:prod'], 'timestamp': 1, 'value': 10}, {'tags': ['host:db'], 'timestamp': 2, 'value': 4}, {'tags': ['host:web'], 'timestamp': 3, 'value': 7}, {'tags': ['host:web', 'env:prod'], 'timestamp': 4, 'value': 3}], 'host:web', 2)
Output: [17, 10]
Example 2
Input: rolling_tag_window_sums([{'tags': ['a'], 'timestamp': 10, 'value': 1.5}, {'tags': ['b'], 'timestamp': 11, 'value': 8}, {'tags': ['a'], 'timestamp': 12, 'value': 2.5}, {'tags': ['a'], 'timestamp': 13, 'value': 4}], 'a', 2)
Output: [4, 6.5]
Example 3
Input: rolling_tag_window_sums([{'tags': ['x'], 'timestamp': 1, 'value': 5}, {'tags': ['y'], 'timestamp': 2, 'value': 6}], 'missing', 1)
Output: []
Hints
Hint 1
Filter the records first, keeping only those whose tags include the target tag, and keep their input order. Then work only with the list of values.
Hint 2
Computing each window from scratch costs O(m*k). Compute the first window once, then update the running sum by adding the value entering on the right and subtracting the value leaving on the left.
Hint 3
Handle the edge cases early: return an empty list when k <= 0 or when there are fewer than k matching values.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
First, make a single pass to collect the values of records whose tag list contains the target tag. Order is preserved because we never sort.
If k is not positive or there are fewer than k values, the answer is an empty list.
Otherwise, compute the first window's sum directly. Then, for each later window, the new sum equals the previous sum plus the value that enters on the right minus the value that leaves on the left. Each update is O(1), and the result is built in order.
Why It Is Correct
Let S_i be the sum of the window starting at index i, so S_i = v_i + ... + v_{i+k-1}. Then S_{i+1} = S_i - v_i + v_{i+k}, because the two windows share v_{i+1} ... v_{i+k-1} and differ only in their endpoints. By induction from the directly computed S_0, every emitted value is the true window sum.
Filtering before windowing is essential. Windows must cover consecutive matching records, not consecutive raw records with non-matches skipped inside them.
Complexity
- Time: O(n * T) to filter, where
nis the number of records andTis the average tag count per record for the membership test. The sliding pass is O(m), wheremis the number of matches. - Space: O(m) for the collected values and O(m - k + 1) for the output.
Edge Cases
k <= 0returns[].- No matches, or
m < k, returns[]. k == mreturns a single sum.k == 1returns the matching values themselves, in input order.- Negative and zero values work unchanged.
from typing import Dict, List
def rolling_tag_window_sums(datapoints: List[Dict], tag: str, k: int) -> List[float]:
"""
Keep the records whose "tags" contain `tag`, in their original order.
Return the sum of "value" over every window of k consecutive kept records.
Return [] if k <= 0 or there are fewer than k matching records.
"""
if k <= 0:
return []
values = [record["value"] for record in datapoints if tag in record["tags"]]
if k > len(values):
return []
window_total = sum(values[:k])
totals = [window_total]
for right in range(k, len(values)):
window_total += values[right] - values[right - k]
totals.append(window_total)
return totals