Music streaming app~40 min2s · 256 MBtarget O(n) time, O(capacity) spacelru · queues · hashing
A streaming app keeps a cache of recently loaded profile pages. The cache has two limits. It holds at most capacity pages, and a page is too old to serve once ttl seconds have passed since it was written.
When the cache is full and a new page arrives, the page that was used least recently makes room. Expired pages are removed first, so they never take a place. You write the cache logic for a log of commands.
Write run_cache(capacity, ttl, commands, args).
commands[i] is "put", "get" or "size". Every args[i] starts with the time of the command in seconds. The times never go down.w with w + ttl <= now."put" has args[i] = [time, key, value]. If the key is live, replace its value and write time. Otherwise, if the cache already has capacity live entries, remove the least recently used one. Then store the entry as the most recently used one, with write time time."get" has args[i] = [time, key]. Return the value of a live key and make it the most recently used one, without changing its write time. Return -1 for a key that is not live."size" has args[i] = [time]. Return the number of live entries."get" and "size" commands, in order.Input: capacity = 2, ttl = 10, commands = ["put", "put", "get", "put", "get", "get", "get", "size"], args = [[0, 1, 10], [1, 2, 20], [2, 1], [3, 3, 30], [4, 2], [5, 1], [10, 1], [11]]
Output: [10, -1, 10, -1, 1]The table shows the live keys, least recently used first.
| Step | Command | Live entries after the command, least recently used first | Output |
|---|---|---|---|
| 1 | put 1 = 10 at 0 | 1 | |
| 2 | put 2 = 20 at 1 | 1, 2 | |
| 3 | get 1 at 2 | 2, 1 | 10 |
| 4 | put 3 = 30 at 3 (full: key 2 leaves) | 1, 3 | |
| 5 | get 2 at 4 | 1, 3 | -1 |
| 6 | get 1 at 5 | 3, 1 | 10 |
| 7 | get 1 at 10 (written at 0, expired at 10) | 3 | -1 |
| 8 | size at 11 | 3 | 1 |
The table lists the live keys after each command. A get makes a key the most recently used one. The put at time 3 finds the cache full and removes key 2. At time 10, key 1 is 10 seconds old, so it has expired.
Input: capacity = 1, ttl = 5, commands = ["put", "put", "get", "get"], args = [[0, 1, 7], [3, 1, 8], [7, 1], [8, 1]]
Output: [8, -1]The second put rewrites key 1 at time 3, so the entry lives until time 8. At time 7 it is live and at time 8 it has expired.
Input: capacity = 1, ttl = 100, commands = ["size"], args = [[0]]
Output: [0]The cache is empty, so its size is 0.
1 ≤ capacity ≤ 100,000 and 1 ≤ ttl ≤ 1,000,000,0001 ≤ commands.length ≤ 100,000, and args has the same lengthA list that is scanned for every command costs up to n × capacity steps, 5 × 10^9 at the limits. A hash map finds a key at once, and an ordered map or a linked list gives the least recently used entry in O(1). Expiry follows a different order: entries expire in the order they were written, so a queue gives the next expiry at its front.