2Brute2Best
πŸ”₯0

LFU Cache

HardΒ·LeetCode #460 Pro OnlyTricky / Edge Case
LeetCode
01

Problem Statement

Build a class LFUCache: a key–value store with a fixed size limit. When it is full and a new key arrives, it throws out the key that has been used the fewest times (the least frequently used, "LFU"). If several keys share that smallest use count, it throws out the one among them that was used longest ago.

  • LFUCache(int capacity) creates an empty cache that can hold at most capacity keys.
  • int get(int key) returns the value of key, or -1 if it is not stored. A successful get adds 1 to the key's use count.
  • void put(int key, int value) stores value under key. If the key exists, its value is replaced and its use count goes up by 1. Otherwise, if the cache is full, the victim described above is removed first; then the new key is added with a use count of 1.

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

Input

The capacity, then a sequence of get(key) and put(key, value) calls.

Output

For each get, the stored value or -1. put returns nothing.

Example 1
Input: capacity = 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: 1, -1, 3, -1, 3, 4 (the results of the six get calls)

After get(1), key 1 has count 2 and key 2 has count 1, so put(3, 3) evicts key 2. After get(3), keys 1 and 3 both have count 2 β€” a tie. Key 1 was used longer ago, so put(4, 4) evicts key 1.

Constraints
  • β€’ 1 ≀ capacity ≀ 10^4 (older versions allowed 0 β€” handle it safely anyway)
  • β€’ 0 ≀ key ≀ 10^5
  • β€’ 0 ≀ value ≀ 10^9
  • β€’ At most 2 Β· 10^5 calls to get and put
02

Pattern Recognition Clues

Recognising these key signals in the problem description immediately identifies the pattern:

β€œget and put in O(1)”
β†’ No scanning β†’ hash maps for every lookup.
β€œleast frequently used”
β†’ Group keys by use count, and know the smallest count without searching β†’ buckets + minFreq.
β€œties broken by least recently used”
β†’ Inside each count group, keep LRU order β†’ one linked list per count.
03

Approach Complexity Ladder

Brute Force β€” vector with count and timestampO(C)O(C)

Store (key, value, freq, lastUsed); scan for the key and for the victim

Better β€” hash map + ordered set of (freq, time)O(log C)O(C)

Map finds keys; a std::set sorted by (freq, time) gives the victim at begin()

Optimal β€” frequency buckets of LRU lists + minFreqO(1)O(C)

freq β†’ list of keys (front = most recent), key β†’ (value, freq, iterator), track minFreq

Brute Force Intuition

Keep a vector of items, each with key, value, freq and lastUsed (a global timer that goes up on every use). get and put scan for the key. To evict, scan for the item with the smallest freq, and on a tie the smallest lastUsed.

Recognition rule for this sub-pattern:

You must support operations in O(1); combine a hash map with another structure (list, array) so each one covers the other's weakness.
Remember this Β· Arrays & Hashing
Trigger
"Have I seen X before?", pairs that add up to a target, grouping things that look alike, counting occurrences.
Think
Instead of scanning again for each element, can I remember earlier elements in a map?
Key question
What exactly do I store as the key, and what as the value?
Brute2Best Pro Content

Unlock Complete Visual Walkthrough & Optimal C++

The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.