Count active cache items at each query time from insertion times and TTLs
Company: Zscaler
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given cache items with insertion times and TTLs, count how many are active at each query time, where each item lives on a half-open interval. Tests whether you can answer many point queries faster than checking every item, and whether you handle items inserted or expiring exactly at the query time.
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
- insertion_time + ttl <= 2 * 10^9 follows from the bounds above and fits in a signed 32-bit integer
Examples
Input: ([[1, 5], [2, 3], [6, 2]], [3, 5, 7])
Expected Output: [2, 1, 1]
Explanation: First source example: [2, 5) has just expired at time 5, and [6, 8) is the only item active at 7.
Input: ([[0, 10], [0, 10], [0, 10]], [0, 5, 9, 10])
Expected Output: [3, 3, 3, 0]
Explanation: Second source example: three identical items active on [0, 10), all expired at time 10.
Hints
- Trace the first example at time 5: the item inserted at time 2 with ttl 3 no longer counts, while an item inserted exactly at a query time does count.
- The answers must follow the order of queries, even though query times can repeat and arrive in any order.
- With up to 10^4 items and 10^4 queries, look for a way to prepare the cache once so that each query costs less than a full scan of every item.