FastPrepLFU Cache

LFU Cache

Citadel logoCitadel● HardFULLTIMEPHONE SCREEN

Updated

Problem statement

Implement a least frequently used (LFU) cache that holds at most capacity keys, and process operations on it. The cache starts empty.

Every key in the cache has a use count. A key's count is 1 when it is added to the cache, and each later get or put of that key adds 1.

Each operation is one of:

  • [0, key, value]: put. If key is in the cache, set its value to value and count one more use. Otherwise add key with value. If the cache already holds capacity keys, first remove the key with the smallest use count. When several keys tie, remove the one whose last get or put is the oldest. Nothing is recorded.
  • [1, key]: get. If key is in the cache, record its value and count one more use. Otherwise record -1.

If capacity is 0, the cache never stores a key. Return the recorded values in operation order. Each operation should take O(1) average time.

Function

lfuCache(capacity: int, operations: int[][]) → int[]

Examples

Example 1

capacity = 2operations = [[0,5,50],[1,5],[1,5],[0,8,80],[0,3,30],[1,8],[1,5],[1,3]]return = [50,50,-1,50,30]

Key 5 is read twice, so it has 3 uses. Key 8 is put next with 1 use, and the cache is now full. Putting key 3 removes key 8, the key with the fewest uses, even though key 5 was used longer ago. So the get of 8 returns -1, and the gets of 5 and 3 return 50 and 30.

Example 2

capacity = 3operations = [[0,1,7],[0,2,4],[0,3,9],[1,2],[0,1,6],[0,4,5],[1,3],[1,4],[0,6,1],[1,2],[1,1]]return = [4,-1,5,-1,6]

The get of key 2 returns 4 and gives key 2 its second use. Putting key 1 again changes its value to 6 and also gives it a second use. Putting key 4 removes key 3, the only key with one use, so the get of 3 returns -1. The get of key 4 returns 5, and now keys 1, 2 and 4 all have 2 uses. Putting key 6 removes key 2, because its last use is the oldest of the three. The get of 2 returns -1 and the get of 1 returns 6.

Example 3

capacity = 0operations = [[0,4,1],[1,4]]return = [-1]

A cache with capacity 0 never stores a key, so the get returns -1.

Constraints

  • 0 <= capacity <= 10^4
  • 1 <= operations.length <= 2 * 10^4
  • Each operation is [0, key, value] or [1, key].
  • 0 <= key <= 10^5
  • 0 <= value <= 10^9

More Citadel Phone Screen questions

Similar questions at other companies

Citadel interview experiences

All Citadel interview questionsSee Citadel hiring insights
Saved
class Solution {
    public int[] lfuCache(int capacity, int[][] operations) {
      // Write your code here.
    }
}
Checking account…