Skip to main content

LFU Cache

HardPremium

Design a least frequently used (LFU) cache. Implement the LFUCache class:

  • LFUCache(capacity) creates a cache that holds at most capacity keys.
  • get(key) returns the key's value if it's in the cache, or -1 if it isn't.
  • put(key, value) sets the key's value, adding the key if it's new.

Every get or put on a key that's in the cache counts as one use of that key, and a newly added key starts with one use. When the cache is full and a new key arrives, first remove the key with the fewest uses. If several keys tie, remove the one that was used least recently.

Both get and put must run in O(1) average time. The tests run a sequence of operations on one cache and check the value returned by every get, in order.

Example 1

Input: ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]] Output: [1, -1, 3, -1, 3, 4]

After get(1), key 1 has two uses and key 2 has one, so put(3, 3) removes key 2. Keys 1 and 3 then both have two uses after get(3). Key 1 was used less recently, so put(4, 4) removes it.

Example 2

Input: ["LFUCache", "put", "get", "put", "get", "get"] [[1], [1, 10], [1], [2, 20], [1], [2]] Output: [10, -1, 20]

With room for one key, adding key 2 removes key 1 even though key 1 has more uses.

Constraints

  • 1 <= capacity <= 10000
  • 0 <= key <= 100000 and 0 <= value <= 10^9
  • At most 200000 calls are made to get and put.