KatInterview

Rolling window totals over filtered records in input order

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingsliding-windowprefix-sumfiltering

Last 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 k records 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.