Payments app~35 min2s · 256 MBtarget O(n) time, O(capacity) spaceclassic twin: lc-460lru · linked-lists · hashing
A payments app converts amounts with exchange rates that come from a slow service. It keeps a cache of at most capacity rates. Some rates, such as the most common currency pairs, are read all day, and others are read once.
A least recently used cache would drop a busy rate after a quiet moment. This cache drops the rate that was used the fewest times instead. When several rates were used the same number of times, it drops the one that was used longest ago. Every read and write must take constant time.
Write run_lfu(capacity, commands, args).
capacity entries. Each entry has a use count.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 add 1 to its use count. Otherwise return -1."put": if the key is in the cache, replace its value and add 1 to its use count. Otherwise add it with a use count of 1."get", in order. A "put" records nothing.Input: capacity = 2, commands = ["put", "put", "get", "get", "put", "get", "get", "put", "get", "get", "get"], args = [[8, 80], [9, 90], [8], [8], [7, 70], [9], [7], [6, 60], [7], [8], [6]]
Output: [80, 80, -1, 70, -1, 80, 60]| Step | Command | Lists by count (oldest use first) | Answer |
|---|---|---|---|
| [1] | start | empty | |
| [5] | put 8, 80 | 1: 8 | |
| [5] | put 9, 90 | 1: 8, 9 | |
| [3] | get 8 | 1: 9; 2: 8 | 80 |
| [3] | get 8 | 1: 9; 3: 8 | 80 |
| [5] | put 7, 70 (removes 9) | 1: 7; 3: 8 | |
| [2] | get 9 | 1: 7; 3: 8 | -1 |
| [3] | get 7 | 2: 7; 3: 8 | 70 |
| [5] | put 6, 60 (removes 7) | 1: 6; 3: 8 | |
| [2] | get 7 | 1: 6; 3: 8 | -1 |
| [3] | get 8 | 1: 6; 4: 8 | 80 |
| [3] | get 6 | 2: 6; 4: 8 | 60 |
Input: capacity = 2, commands = ["put", "put", "put", "get", "get"], args = [[1, 10], [2, 20], [3, 30], [1], [2]]
Output: [-1, 20]Keys 1 and 2 were each used once. Key 1 was used longer ago, so it is removed when key 3 arrives.
Input: capacity = 1, commands = ["get"], args = [[5]]
Output: [-1]1 ≤ capacity ≤ 100,0001 ≤ commands.length = args.length ≤ 100,000Scanning all entries to find the one with the smallest count, and the oldest among ties, costs up to capacity steps for each new key. With a full cache of 50,000 entries, that is about 5 × 10^9 steps for 10^5 commands.
Keeping one list for each use count, and the smallest count in a variable, finds the entry to remove in one step.