Implement an LFU cache
SalesforceSoftware Engineer · OnsiteLast updated
This question evaluates understanding of data structures and cache eviction policies, specifically frequency tracking for LFU caches and LRU tie-breaking among equal-frequency items.
Problem: LFU Cache
Design and implement a Least Frequently Used (LFU) cache with a fixed capacity.
The cache supports the following operations:
-
get(key) -> value -
Return the value of
keyif it exists in the cache. -
Otherwise return
-1. -
If the key exists, its usage frequency increases by 1.
-
put(key, value) -> void -
Insert or update the value of
key. -
If the cache reaches capacity, it must evict one key before inserting.
Eviction Policy
- Evict the key with the lowest frequency (LFU).
- If multiple keys have the same (lowest) frequency, evict the least recently used (LRU) among them.
Requirements / Constraints
- Capacity is a non-negative integer.
- Aim for O(1) average time per operation.
- If
capacity == 0,putdoes nothing andgetalways returns-1.
Example
If capacity = 2:
put(1, 1)put(2, 2)get(1)returns1(freq(1)=2)put(3, 3)evicts key2(freq(2)=1 is lowest)get(2)returns-1get(3)returns3
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.