LFU Cache

Try to solve the LFU Cache problem.

Statement

Design and implement a data structure for a Least Frequently Used (LFU) cache.

Implement the LFUCache struct. Here is how it should be implemented:

  • NewLFUCache(capacity): This function initializes the object with the capacity of the data structure.

  • Get(key): This function gets the value of the key if it exists in the cache. Otherwise, it returns -1.

  • Put(key, value): This function updates the value of the key if present, or inserts the key if it’s not present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there’s a tie, that is, two or more keys have the same frequency, the least recently used key is invalidated.

To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the Put() operation). The use counter for a key in the cache is incremented and either a Get() or Put() operation is called on it.

The Get() and Put() functions should both run with an average time complexity of O(1)O(1).

Constraints:

  • 0≤0 \leq capacity ≤104\leq 10^4

  • 0≤0 \leq key ≤105\leq 10^5

  • 0≤0 \leq value ≤105\leq 10^5

  • At most 2×1032 \times 10^3 calls will be made to Get() and Put().

Examples

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy