Engineering platform~30 min2s · 256 MBtarget O(n) time, O(capacity) spaceclassic twin: lc-146lru · linked-lists · hashing
A platform service reads configuration entries from a slow store. It keeps the most recent ones in a small cache in memory. The cache holds at most capacity entries.
When a new entry arrives and the cache is full, it drops the entry that was used least recently. Reading an entry counts as using it, and so does writing it. Every read and every write must take constant time, even with 100,000 entries in the cache.
Write run_cache(capacity, commands, args).
capacity entries.commands[i] is "get" or "put". For "get", args[i] is [key]. For "put", args[i] is [key, value]."get": if the key is in the cache, return its value and make it the most recently used. Otherwise return -1."put": store the value under the key and make it the most recently used. If the key was already there, its value is replaced. If the cache now holds more than capacity entries, remove the least recently used one."get", in order. A "put" records nothing.Input: capacity = 3, commands = ["put", "put", "put", "get", "put", "get", "put", "put", "get", "get"], args = [[5, 50], [6, 60], [7, 70], [5], [8, 80], [6], [7, 71], [9, 90], [5], [7]]
Output: [50, -1, -1, 71]| Step | Command | Cache, most recent first (key: value) | Answer |
|---|---|---|---|
| [1] | start | empty | |
| [3] | put 5, 50 | 5: 50 | |
| [3] | put 6, 60 | 6: 60, 5: 50 | |
| [3] | put 7, 70 | 7: 70, 6: 60, 5: 50 | |
| [4] | get 5 | 5: 50, 7: 70, 6: 60 | 50 |
| [3] | put 8, 80 (evicts 6) | 8: 80, 5: 50, 7: 70 | |
| [2] | get 6 | 8: 80, 5: 50, 7: 70 | -1 |
| [4] | put 7, 71 | 7: 71, 8: 80, 5: 50 | |
| [3] | put 9, 90 (evicts 5) | 9: 90, 7: 71, 8: 80 | |
| [2] | get 5 | 9: 90, 7: 71, 8: 80 | -1 |
| [4] | get 7 | 7: 71, 9: 90, 8: 80 | 71 |
Input: capacity = 1, commands = ["put", "put", "get", "get"], args = [[1, 10], [2, 20], [1], [2]]
Output: [-1, 20]With room for one entry, each put replaces the last.
Input: capacity = 2, commands = ["get"], args = [[4]]
Output: [-1]A key that was never stored gives -1.
1 ≤ capacity ≤ 100,0001 ≤ commands.length = args.length ≤ 100,000Keeping the entries in a list ordered by use, and scanning the list for each command, costs up to capacity steps each time. With a full cache of 50,000 entries and 10^5 commands, that is about 5 × 10^9 steps.
A hash map finds an entry in one step, and a doubly linked list moves it to the front in a few pointer changes.