You receive a list of events in time order. Each event is [timestamp, value]. You are also given a positive integer window_size. For each event, compute the average of the values of all events whose timestamps fall within the window [timestamp - window_size + 1, timestamp], counting the current event and the events before it in the list. Return the averages in the same order as the events.
Function Signature
def windowed_average(events: list[list[int]], window_size: int) -> list[float]:
...
Rules
-
events[i] = [timestamp, value]
, and timestamps are in non-decreasing order.
-
The window for event
i
with timestamp
t
is the closed interval
[t - window_size + 1, t]
. Its start can be negative.
-
Only events at index
i
or earlier count toward the average for event
i
. A later event with the same timestamp is not included yet (see Example 2).
-
The current event is always inside its own window, so no window is empty.
-
Each average is the sum of the values in the window divided by their count, returned as a float. Answers within
1e-5
of the exact value are accepted.
Constraints
-
1 <= len(events) <= 10^5
-
0 <= timestamp <= 10^9
-
Timestamps are in non-decreasing order.
-
-10^4 <= value <= 10^4
-
1 <= window_size <= 10^9
Examples
Input: events = [[1, 10], [2, 20], [3, 30], [5, 40], [6, 50]], window_size = 3
Output: [10.0, 15.0, 20.0, 35.0, 45.0]
At t=1 the window is [-1, 1] and holds only 10, and at t=3 the window [1, 3] holds 10, 20 and 30 (average 20). At t=5 the window [3, 5] has dropped the events at t=1 and t=2 and keeps 30 and 40 (average 35), and at t=6 the window [4, 6] keeps 40 and 50 (average 45).
Input: events = [[1, 5], [1, 15], [2, 10], [10, 100]], window_size = 2
Output: [5.0, 10.0, 10.0, 100.0]
The first event at t=1 sees only itself because the second t=1 event comes later in the list, and the second one sees 5 and 15. At t=2 the window [1, 2] holds 5, 15 and 10 (average 10), and at t=10 the window [9, 10] holds only 100.
Input: events = [[0, 3], [4, -1], [5, 4]], window_size = 2
Output: [3.0, -1.0, 1.5]
At t=4 the window [3, 4] no longer contains the event at t=0, so the average is -1. At t=5 the window [4, 5] holds -1 and 4, which average to 1.5.