Design a TTL key-value cache that returns the average of unexpired values
Company: Confluent
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a data structure that stores key-value pairs where each entry has a time-to-live (TTL). An entry inserted at time `timestamp` with TTL `ttl` expires at time `timestamp + ttl`. From that point on it must not be returned or included in calculations, so an entry is live at time `t` only while `t < timestamp + ttl`.
The cache should support inserting and updating entries, retrieving values by key (only if not expired), deleting entries manually, and computing the average of all non-expired values at a given point in time.
All time-based operations use a logical timestamp passed as an argument, not real wall-clock time. Timestamps across all calls are guaranteed to be non-decreasing.
Implement the following methods:
- `put(key: str, value: int, ttl: int, timestamp: int)`: Insert or update a key-value pair. The entry expires at `timestamp + ttl`.
- `get(key: str, timestamp: int) -> int`: Return the value for the key if it exists and has not expired at the given timestamp. Otherwise return `-1`.
- `remove(key: str) -> bool`: Remove the key from the cache. Return `True` if the key existed, `False` otherwise.
- `getWindowedAverage(timestamp: int) -> float`: Return the average of all non-expired values at the given timestamp. Return `0.0` if no valid entries exist.
```hint What non-decreasing time buys you
Once an entry is expired at some call, can it ever be live again at a later call? Think about what that allows you to do with expired entries.
```
```hint If the average is called a lot
A full scan per average call is the simple answer. To do better, think about which quantities you could keep up to date on every write, and how to retire entries in the order they expire.
```
### Examples
Example 1:
```python
cache = WindowedAverageCache()
cache.put("a", 10, 5, 1) # "a" = 10, expires at 6
cache.put("b", 20, 10, 2) # "b" = 20, expires at 12
cache.getWindowedAverage(3) # -> 15.0 ((10 + 20) / 2)
cache.put("a", 40, 5, 4) # "a" updated to 40, now expires at 9
cache.getWindowedAverage(5) # -> 30.0 ((40 + 20) / 2, the old 10 no longer counts)
cache.get("a", 9) # -> -1 ("a" expired at 9)
cache.getWindowedAverage(9) # -> 20.0 (only "b" is live)
cache.getWindowedAverage(12) # -> 0.0 ("b" expired at 12)
```
Example 2:
```text
Input:
["WindowedAverageCache", "getWindowedAverage", "put", "get", "remove", "get", "getWindowedAverage"]
[[], [0], ["x", 100, 10, 1], ["x", 5], ["x"], ["x", 5], [5]]
Output: [null, 0.0, null, 100, true, -1, 0.0]
```
```python
cache = WindowedAverageCache() # empty cache
cache.getWindowedAverage(0) # -> 0.0 (no entries)
cache.put("x", 100, 10, 1) # "x" = 100, expires at 11
cache.get("x", 5) # -> 100 (5 < 11, not expired)
cache.remove("x") # -> True ("x" was present and is removed)
cache.get("x", 5) # -> -1 ("x" was removed)
cache.getWindowedAverage(5) # -> 0.0 (no entries)
```
### Constraints & Assumptions
- `1 <= key.length <= 100`, and keys consist of lowercase English letters and digits.
- `-10^6 <= value <= 10^6`, so values can be negative or zero.
- `1 <= ttl <= 10^9`.
- Timestamps are non-decreasing across all calls.
- `getWindowedAverage` returns `0.0` if no non-expired entries exist.
### Clarifying Questions to Ask
- `remove` takes no timestamp. Should it return `False` for a key whose entry had already expired as of the latest timestamp the cache has seen?
- How often is `getWindowedAverage` called compared with `put` and `get`? A linear scan is fine for occasional calls and too slow if the average is read after every write.
- Is the cache used from a single thread, or must the methods be safe under concurrent calls?
### What a Strong Answer Covers
- One expiry rule applied the same way in every method, including the boundary at `timestamp + ttl`.
- Updates that replace both the value and the expiration, so the old value stops counting toward the average.
- Why lazy cleanup is safe given non-decreasing timestamps, and how `remove` treats a key that has expired but is still stored.
- The cost of each operation, and a design that makes `getWindowedAverage` cheaper than a full scan when it is called often.
- Edge cases such as an empty cache, negative values, and a key that is removed and then inserted again.
### Follow-up Questions
- Make `getWindowedAverage` run in O(1) amortized time. What extra state do you keep, and what do `put` and `get` cost after the change?
- What breaks if timestamps can arrive out of order, and how would you redesign the cache for that?
- How would you make the cache safe to call from multiple threads?
- How would you also cap the cache at a fixed number of live entries, and which entry would you evict first?
Overview: Design an in-memory key-value cache where every entry has its own time-to-live and the cache can report the average of all unexpired values at a logical timestamp. It tests hash map design, lazy expiry under non-decreasing timestamps, and keeping a running aggregate correct across updates and removals.