Problem 460

Abstract / Summary

Design a cache that removes least frequently used items and if tied the least recently used among them.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0460.py

class LFUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.data  = defaultdict(int)  # (key, value)
        self.used  = defaultdict(int)  # (key, numUsed)
        self.freq  = defaultdict(list) # (numUsed, (key1, key2, ...)) keys sorted by age
        self.least = 0                 # min(self.freq)

    # internal function: updates LFU counters, key MUST exist
    def access(self, key):
        # increment usage counter
        previous = self.used[key]
        current  = previous + 1
        self.used[key] = current # or += 1

        # update self.freq
        self.freq[current ].append(key)
        self.freq[previous].remove(key)
        if not self.freq[previous]: # no item left with old count
            self.freq.pop(previous)
            # maybe it was the least frequent item
            if previous == self.least:
                self.least = current # or += 1

    def get(self, key: int) -> int:
        if key not in self.data:
            return -1 # unknown

        self.access(key)
        return self.data[key]

    def put(self, key: int, value: int) -> None:
        # overwrite an existing item
        if key in self.data:
            self.access(key) # update LFU counters
            self.data[key] = value
            return

        # evict an item
        if len(self.data) == self.capacity:
            # remove this key from all data structures
            evict = self.freq[self.least].pop(0)
            if not self.freq[self.least]:
                self.freq.pop(self.least)
            self.used.pop(evict)
            self.data.pop(evict)

        # now there's at least one slot avaiable for this shiny new item
        self.data[key] = value
        self.used[key] = 1
        self.least     = 1
        self.freq[1].append(key)
52 lines | 1869 bytes | submitted February 27, 2024 | GitHub   45% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (800k+ submissions).

Typical patterns to solve this problem:
  • Design
  • Doubly Linked List
  • Hash Table
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The class implements a Least-Frequently-Used (LFU) cache with a fixed capacity. It stores key-value pairs and tracks how often each key is accessed. When the cache reaches its limit, the entry with the smallest access count (and the oldest among ties) is evicted. The implementation relies on three hash-based containers to achieve constant-time updates and look-ups.

Initialization

The constructor receives the maximum number of entries the cache may hold. Three defaultdict objects are created:

  • data maps a key to its stored value.
  • used maps a key to the number of times it has been accessed.
  • freq maps an access count to a list of keys that share that count, preserving insertion order to break ties by age.

A variable least records the smallest access count currently present, allowing quick identification of the eviction candidate.

def __init__(self, capacity: int):
    self.capacity = capacity
    self.data  = defaultdict(int)   # key → value
    self.used  = defaultdict(int)   # key → access count
    self.freq  = defaultdict(list)  # count → [keys in age order]
    self.least = 0                  # current minimum count

Access Update Logic

The internal access method is invoked whenever a key that already exists in the cache is read or overwritten. It increments the key’s usage counter, moves the key from the list belonging to the old count to the list for the new count, and adjusts least when the old count list becomes empty. This keeps the frequency structure synchronized with the actual usage statistics.

def access(self, key):
    previous = self.used[key]
    current  = previous + 1
    self.used[key] = current

    self.freq[current].append(key)
    self.freq[previous].remove(key)
    if not self.freq[previous]:
        self.freq.pop(previous)
        if previous == self.least:
            self.least = current

Get Operation

get first checks whether the requested key is present. If it is missing, the method returns -1. When the key exists, access is called to update its usage statistics, and the stored value is returned. This ensures that reads contribute to the LFU ordering.

def get(self, key: int) -> int:
    if key not in self.data:
        return -1
    self.access(key)
    return self.data[key]

Put Operation

put handles three distinct situations: overwriting an existing entry, evicting the least-frequently-used entry when the cache is full, and inserting a brand-new entry.

When the key already exists, the method updates its usage count via access and replaces the stored value. No eviction occurs because the entry remains in the cache.

If the cache is at capacity and the key is new, the method evicts the first key from the list associated with least. Because the list preserves age order, the oldest key among those with the minimal count is removed. After eviction, the new key is inserted with an initial usage count of 1, and least is reset to 1.

def put(self, key: int, value: int) -> None:
    if key in self.data:
        self.access(key)
        self.data[key] = value
        return

    if len(self.data) == self.capacity:
        evict = self.freq[self.least].pop(0)
        if not self.freq[self.least]:
            self.freq.pop(self.least)
        self.used.pop(evict)
        self.data.pop(evict)

    self.data[key] = value
    self.used[key] = 1
    self.least = 1
    self.freq[1].append(key)

Edge Cases Handled

The implementation gracefully deals with a request for a non-existent key by returning -1 without altering internal state. When the cache is empty, least starts at 0 and is updated to 1 upon the first insertion, ensuring that subsequent eviction logic has a valid baseline. During eviction, the code checks whether the list for the current least count becomes empty after removing an entry; if so, the corresponding entry in freq is removed, preventing stale empty lists from lingering. The access method also updates least when the smallest count list disappears, guaranteeing that least always reflects the true minimum usage count.

If the capacity is set to zero, the eviction block will trigger on every insertion attempt, effectively discarding any new entry immediately. The code still maintains correct internal structures because the eviction path removes the placeholder before the new entry is added, leaving the cache empty as intended.

Performance Optimizations

The design leverages hash-based containers (defaultdict) to achieve constant-time look-ups for keys, usage counts, and frequency buckets. By storing keys in lists within each frequency bucket, the implementation can quickly identify the oldest key with the minimal count via pop(0). Maintaining the least variable eliminates the need to scan the frequency map when determining which bucket to evict from, turning eviction into a direct operation. Updating the usage count moves a key between two lists without rebuilding any structures, and the conditional removal of empty frequency buckets keeps the freq map compact, reducing memory overhead. These choices collectively ensure that both read and write paths execute with minimal overhead, suitable for high-throughput caching scenarios.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a small toy box that can only hold a few toys at a time. Because the box is small, you have to be very careful about which toys stay inside. This code acts like a helper who decides which toys get to stay and which ones need to go back on the shelf.

When you want to play with a toy, the helper looks to see if it is already in the box. If it is, the helper notices you played with it one more time. The helper keeps a secret tally of how many times you have played with every toy in the box.

If you bring a new toy to put in the box and there is no room left, the helper looks at the tally. The helper finds the toy that has been played with the least amount of times and takes it out to make space for the new one. This ensures that the toys you use the most are always inside ready for you to grab.

When you ask for a toy, the helper quickly checks if it is hidden in the box. If it is there, the helper does the same magic to show how much you love that toy before giving it to you. If the box gets too full, the helper gently kicks out the toys that nobody wants to play with lately, keeping the favorites right there in the box for the next game.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5 | μ = 5.00 | σ = 1.98

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong TS
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong TypeScript
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
41 links | 27 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   February 27, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality