LFU Cache

Hard Design

Problem

Design a cache with a fixed capacity that evicts the least frequently used key when it is full. If several keys share that lowest frequency, evict the least recently used among them. get and put should be average O(1). Missing keys return -1.

Original: LeetCode 460: LFU Cache.

Examples

Example 1

Input`LFUCache: LFUCache(2), put(1, 1), put(2, 2), get(1), put(3, 3), get(2), get(3), put(4, 4), get(1), get(3), get(4)`
Output`[null, null, null, 1, null, -1, 3, null, -1, 3, 4]`

Constraints

  • 1 <= capacity <= 10^4
  • 0 <= key <= 10^5
  • 0 <= value <= 10^9
  • At most 2 * 10^5 calls will be made to get and put.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 460: LFU Cacheleetcode.com
  2. Java SE 17 API: LinkedHashSetdocs.oracle.com