This is a design round. You write the classes, and the interviewer checks that they behave.
Here you build LFUCache, a cache that holds a few keys with their values. When it is full, it drops the key used the fewest times.
Implement the class:
new LFUCache(capacity)makes an empty cache for at mostcapacitykeys.Get(key)returns the value ofkey, or -1 whenkeyisn't in the cache.Put(key, value)storesvalueunderkey.Uses(key)returns how many useskeyhas had since it came into the cache.
A call to Get that finds the key counts as one use of it. A call that returns -1 changes nothing.
A Put on a key in the cache replaces its value. It also counts as one use.
A Put on a new key adds it with 1 use. That Put is its first use.
When the cache is full, a new key first makes one key leave. The key that leaves has the fewest uses. On a tie, the key whose last use is the oldest leaves.
A key that leaves loses its uses. If it comes back later, it starts again at 1 use.
A call to Uses is not a use. It returns 0 for a key that isn't in the cache.
The calls run in order on one new LFUCache. A call to Put writes nothing. A call to Get or Uses writes the number it returns.
Example 1:
Input: new LFUCache(2) 1. Put(1, 10) 2. Put(2, 20) 3. Get(1) 4. Put(3, 30) 5. Get(2) 6. Get(3) 7. Uses(1) 8. Uses(3) Output: 10 -1 30 2 2 Explanation: Call 3 is the second use of key 1. Key 2 has only 1 use. The cache is full when key 3 comes in. Key 2 has the fewest uses, so it leaves. That is why call 5 returns -1. Key 3 has 2 uses: its Put and call 6.
Example 2:
Input: new LFUCache(3) 1. Put(5, 50) 2. Put(6, 60) 3. Put(7, 70) 4. Get(6) 5. Get(5) 6. Put(7, 77) 7. Put(8, 80) 8. Get(6) 9. Get(7) 10. Uses(5) 11. Uses(8) Output: 60 50 -1 77 2 1 Explanation: Call 6 changes the value of key 7. It adds no key. After call 6, keys 5, 6 and 7 have 2 uses each. Key 6 was last used in call 4, the oldest of the three. So key 6 leaves when key 8 comes in. Call 9 is the third use of key 7.
Example 3:
Input: new LFUCache(2) 1. Put(4, 40) 2. Get(4) 3. Get(4) 4. Put(9, 90) 5. Put(3, 30) 6. Uses(9) 7. Put(9, 99) 8. Uses(9) 9. Uses(4) 10. Uses(4) Output: 40 40 0 1 3 3 Explanation: After call 3, key 4 has 3 uses. Key 9 came in last, but it has only 1 use. So key 9 leaves in call 5, and call 6 returns 0. In call 7, key 9 comes back and key 3 leaves. Key 9 starts again at 1 use. A call to Uses is not a use. So calls 9 and 10 both return 3.
Constraints:
capacityis from 1 to 10,000.- Each key is a whole number from 0 to 1,000,000,000.
- Each value is a whole number from 0 to 1,000,000,000.
- At most 100,000 calls follow the constructor.
Note:
Each call to Get, Put and Uses should run in O(1) time. Looking through every key for the one to drop would take O(n) time, for n keys.
Free plan: 30 tutor messages. PRO is unlimited.
