Problem · Design
LFU Cache
Learn this problemProblem statement
Implement a least-frequently-used cache with positive integer capacity. Process each command in operations in order:
put key valueinserts a new key or updates an existing key.get keyreturns the stored value, or-1when the key is absent.remove keydeletes the key when present and otherwise has no effect.
A successful get and a put that updates an existing key each increase that key's access frequency by one and make it most recently used within its new frequency. A newly inserted key starts with frequency one.
When insertion exceeds capacity, evict a key with the smallest frequency. If several keys share that frequency, evict the least recently used one. Return the results of the get commands in order.
Function
processLfuCache(capacity: int, operations: String[]) → int[]Examples
Example 1
capacity = 2operations = ["put 1 10","put 2 20","get 1","remove 1","get 1","put 3 30","get 2","get 3"]return = [10,-1,20,30]Reading key 1 returns 10. Removing it makes the next read miss. Keys 2 and 3 then remain in the two-entry cache.
Example 2
capacity = 2operations = ["put 1 1","put 2 2","get 1","put 3 3","remove 1","get 1","get 3"]return = [1,-1,3]The read raises key 1 above key 2, so inserting key 3 evicts key 2. Removing key 1 makes the later read miss.
Constraints
1 <= capacity <= 10000.1 <= operations.length <= 200000.- Each operation is exactly
get key,put key value, orremove key. - Every key and value fits in a signed 32-bit integer.