LFU Cache
Beginner Mode

Problem Statement

Implement a cache that follows the Least Frequently Used (LFU) eviction policy.

When the cache reaches its capacity and a new key needs to be inserted, the key with the lowest access frequency is removed. If there is a tie (multiple keys with the same lowest frequency), the least recently used key among them is evicted.

A frequency counter is maintained for each key. It starts at 1 when a key is first inserted (via put), and increments by 1 each time get or put is called on that key.

Implement the LFUCache class:

  • LFUCache(int capacity) initializes the cache with the given positive capacity.
  • int get(int key) returns the value associated with key if it exists, otherwise returns -1.
  • void put(int key, int value) inserts or updates the key-value pair. If inserting a new key would exceed the capacity, the least frequently used key is evicted first (with LRU tie-breaking).

Both get and put must run in O(1) average time complexity.

Additional information

  • 1 <= capacity <= 1000
  • 0 <= key <= 10000
  • 0 <= value <= 10000

Example 1:

Input:
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 10], [2, 20], [1], [3, 30], [2], [3], [4, 40], [1], [3], [4]]

Output: [null, null, null, 10, null, -1, 30, null, -1, 30, 40]

Explanation:

  • put(1, 10), put(2, 20) -- both have freq=1
  • get(1) -- returns 10, freq(1) becomes 2
  • put(3, 30) -- cache full, key 2 has lowest freq (1), evict it
  • get(2) -- returns -1 (evicted)
  • get(3) -- returns 30, freq(3) becomes 2
  • put(4, 40) -- keys 1 and 3 both have freq=2, but key 1 was used less recently, evict it
  • get(1) -- returns -1 (evicted)
  • get(3) -- returns 30
  • get(4) -- returns 40

Example 2:

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

Output: [null, null, 10, null, 20, -1]
Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →