You are given a 2D integer array cache where cache[i] = [insertion_time, ttl] represents a cache item that was inserted at time insertion_time with a time-to-live (TTL) of ttl time units.
A cache item is considered active at time q if insertion_time <= q < insertion_time + ttl.
You are also given an integer array queries where each element is a query time. For each query time, return the number of cache items that are active at that time.
Function Signature
def count_active_items(cache: list[list[int]], queries: list[int]) -> list[int]:
Rules
-
An item is active from its insertion time inclusive up to
insertion_time + ttl
exclusive.
-
Return one count per query, in the same order as
queries
.
Constraints
-
1 <= len(cache) <= 10^4
-
len(cache[i]) == 2
-
0 <= cache[i][0] <= 10^9
-
1 <= cache[i][1] <= 10^9
-
1 <= len(queries) <= 10^4
-
0 <= queries[j] <= 10^9
Examples
Input: cache = [[1, 5], [2, 3], [6, 2]], queries = [3, 5, 7]
Output: [2, 1, 1]
The items are active on [1, 6), [2, 5) and [6, 8). At time 3 the first two are active. At time 5 only [1, 6) is active, because [2, 5) has just expired. At time 7 only [6, 8) is active.
Input: cache = [[0, 10], [0, 10], [0, 10]], queries = [0, 5, 9, 10]
Output: [3, 3, 3, 0]
All three items are active on [0, 10), so times 0, 5 and 9 each see 3 items. At time 10 all of them have expired.