Problem 146

Abstract / Summary

Design a cache that stores key value pairs and removes the least recently used item when full.

Note

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

C++ 0146.cpp

class LRUCache {
    typedef pair<int, int> Item;                  // key, value
    unordered_map<int, list<Item>::iterator> pos; // key => where in lru
    list<Item> lru;                               // ordered by least recent use
    int maxsize;

public:
    LRUCache(int capacity)
    : maxsize(capacity)
    { }

    int get(int key) {
        if (pos.count(key) == 0)
            return -1;

        auto value = pos[key]->second;

        // move to front
        lru.erase(pos[key]);
        lru.push_front({ key, value });
        pos[key] = lru.begin();

        return value;
    }

    void put(int key, int value) {
        if (pos.count(key) == 0)
        {
            // evict
            if (pos.size() == maxsize)
            {
                auto oldest = lru.back().first;
                lru.erase(prev(lru.end()));
                pos.erase(oldest);
            }
        }
        else
            lru.erase(pos[key]);

        // move to front
        lru.push_front({ key, value });
        pos[key] = lru.begin();
    }
};
44 lines | 1097 bytes | submitted September 2, 2023 | GitHub   17% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (5+ million 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 presented LRUCache class implements a fixed-capacity cache that discards the least-recently used entry when a new item must be stored and the cache is full. It combines an unordered_map for constant-time key lookup with a doubly-linked list that records usage order. The map stores an iterator pointing to the corresponding list node, allowing the cache to relocate or remove entries without traversing the list.

Core Data Structures

The cache maintains three private members:

typedef pair<int, int> Item;                  // key, value
unordered_map<int, list<Item>::iterator> pos; // key => iterator in lru
list<Item> lru;                               // most recent at front
int maxsize;
  • Item is a simple pair holding a key and its associated value.
  • pos maps each key to the exact position of its node inside lru.
  • lru holds the items ordered from most recent (front) to least recent (back).
  • maxsize records the capacity supplied at construction.

Construction

The constructor stores the capacity and leaves the containers empty:

LRUCache(int capacity)
: maxsize(capacity)
{ }

No additional allocation occurs; the standard containers grow lazily as items are inserted.

Retrieval (get)

The get method first checks whether the key exists in pos. If the key is absent, it returns -1. When the key is present, the method extracts the stored value, removes the node from its current position, reinserts it at the front of lru, and updates the iterator stored in pos. This sequence promotes the accessed entry to “most recent”.

int get(int key) {
    if (pos.count(key) == 0)
        return -1;

    auto value = pos[key]->second;

    // move to front
    lru.erase(pos[key]);
    lru.push_front({ key, value });
    pos[key] = lru.begin();

    return value;
}

Edge Cases Handled

  • Missing key - The early count test prevents dereferencing a non-existent iterator.
  • Single-element cache - Erasing and re-adding the sole node still results in a valid front iterator.
  • Repeated accesses - Each successful get moves the node to the front, ensuring that subsequent put operations treat it as most recent.

Insertion / Update (put)

The put method distinguishes between inserting a brand-new key and updating an existing one.

void put(int key, int value) {
    if (pos.count(key) == 0)
    {
        // evict if needed
        if (pos.size() == maxsize)
        {
            auto oldest = lru.back().first;
            lru.erase(prev(lru.end()));
            pos.erase(oldest);
        }
    }
    else
        lru.erase(pos[key]);

    // move to front
    lru.push_front({ key, value });
    pos[key] = lru.begin();
}
  • When the key is absent and the cache has reached its capacity, the method evicts the least-recently used entry. It obtains the key of the back node (lru.back().first), removes that node with erase(prev(lru.end())), and erases the corresponding map entry.
  • If the key already exists, the method removes its current node before re-inserting the updated value at the front.
  • Finally, the new or updated node is placed at the front of lru, and pos is refreshed to point to the new iterator.

Edge Cases Handled

  • Insertion into a full cache - The eviction block runs only when pos.size() equals maxsize, guaranteeing that the cache never exceeds its limit.
  • Updating an existing key - The existing node is removed before the new node is added, preventing duplicate entries for the same key.
  • Zero capacity - If maxsize is zero, the condition pos.size() == maxsize is true on every insertion, causing immediate eviction of the newly added node. The cache therefore remains empty, and any subsequent get will return -1.
  • Repeated put for the same key - The code consistently moves the key to the front, ensuring that the most recent value is also the most recent usage.

Performance Optimizations

The design leverages two complementary STL containers to achieve constant-time operations for the core cache actions:

  • Direct iterator access - By storing an iterator to each list node in pos, the cache avoids linear scans when moving or deleting entries. Both erase(pos[key]) and pos[key] = lru.begin() are O(1).
  • Doubly-linked list for ordering - list provides O(1) insertion at the front (push_front) and O(1) removal of the back element (erase(prev(lru.end()))). This makes the eviction step inexpensive regardless of cache size.
  • Unordered map for lookup - unordered_map supplies average-case O(1) key existence checks (count) and iterator retrieval (pos[key]).
  • Minimal copying - The code moves only the key/value pair needed for the front insertion; the rest of the list remains untouched.

Together, these choices keep the cache’s operational cost independent of the number of stored items, which is essential for high-throughput scenarios where many get and put calls occur.

Consistency Management

Every mutation of the cache updates both lru and pos in lockstep:

  • After erasing a node, the corresponding map entry is either removed (eviction) or overwritten with the iterator to the newly inserted front node.
  • The front insertion always follows an erase, guaranteeing that the list never contains stale iterators.

This tight coupling ensures that the map and list remain synchronized, preventing mismatches between the recorded positions and the actual list contents.

Conclusion

The LRUCache implementation combines an unordered_map and a list to deliver fast, deterministic behavior for both lookups and updates while respecting a fixed capacity. It explicitly handles missing keys, capacity limits, duplicate insertions, and zero-capacity configurations. The use of iterators stored in the map eliminates linear traversals, and the choice of container operations (front insertion, back removal) provides constant-time performance for the essential cache operations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a toy box that only has enough room for a few special treasures. This code acts like a helper who manages those toys.

The toy box is organized so that the toy you played with most recently is always sitting right at the very front. Whenever you want to play with a toy, the helper looks for it. If it is already in the box, the helper takes it out and moves it to the front so it is ready for next time.

If you bring a new toy to put into the box, the helper first checks if there is still an empty spot. If the box is already full, the helper looks all the way to the back to find the toy that has not been played with for the longest time. That old toy gets taken out of the box to make space for the new one. After the new toy goes into the front spot, it becomes the newest treasure. This way, the box stays nice and tidy with all the current favorites staying exactly where they are easy to reach.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.81 | σ = 0.61

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Rust Java JS TS Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++ TS
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++, TypeScript
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
61 links | 43 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LRU Cache | Brute Force | Optimal | Detailed | Leetcode 146'
codestorywithMIK 41 mins
LRU Cache | Brute Force | Optimal | Detailed | Leetcode 146
YouTube video 'LeetCode | 146 LRU Cache | C++ | Explanation'
ygongcode 20 mins
LeetCode | 146 LRU Cache | C++ | Explanation
YouTube video 'LRU Cache | (C++, Java, Python) |30 day Challenge | Day 24 | LeetCode #146'
Knowledge Center 30 mins
LRU Cache | (C++, Java, Python) |30 day Challenge | Day 24 | LeetCode #146
YouTube video 'LRU cache | Live Coding with Explanation | Leetcode #146'
Algorithms Made Easy 10 mins
LRU cache | Live Coding with Explanation | Leetcode #146
YouTube video 'LRU Cache || Leetcode 146 || Variant Question Big Tech Actually Asks'
Coding with Minmer 24 mins
LRU Cache || Leetcode 146 || Variant Question Big Tech Actually Asks
YouTube video 'LRU CACHE | LEETCODE 146 | PYTHON LINKED LIST SOLUTION'
Cracking FAANG 16 mins
LRU CACHE | LEETCODE 146 | PYTHON LINKED LIST SOLUTION
YouTube video '[Java] Leetcode 146. LRU Cache [Design #1]'
Eric Programming 17 mins
[Java] Leetcode 146. LRU Cache [Design #1]
YouTube video 'LRU Cache - 146. LeetCode - Java'
Teddy Smith 13 mins
LRU Cache - 146. LeetCode - Java
YouTube video '146. LRU Cache | Day 016 | 2 Ways | Doubly Linked List | In Build Libraries'
Aryan Mittal 21 mins
146. LRU Cache | Day 016 | 2 Ways | Doubly Linked List | In Build Libraries
YouTube video 'LeetCode 146. LRU Cache 中文解释 Chinese Version'
happygirlzt 14 mins
LeetCode 146. LRU Cache 中文解释 Chinese Version
YouTube video 'LeetCode 146. LRU Cache Explanation with Examples'
happygirlzt 15 mins
LeetCode 146. LRU Cache Explanation with Examples
YouTube video '146. LRU Cache | Daily Leetcode Challenge | July | C++ | Java'
Mayur Programming Club 30 mins
146. LRU Cache | Daily Leetcode Challenge | July | C++ | Java
YouTube video 'LeetCode 146 LRU Cache'
Jeevan Kumar - Cracckify 14 mins
LeetCode 146 LRU Cache
YouTube video 'Google Engineer Explains - LeetCode #146 - LRU Cache - Solution (Python)'
Google Engineer Explains 41 mins
Google Engineer Explains - LeetCode #146 - LRU Cache - Solution (Python)
YouTube video '146 || LRU Cache || C++ || Leetcode Daily Challenge'
CodeFreaks 18 mins
146 || LRU Cache || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #1204: Jul 18, 2023 - 146. LRU Cache'
Programming Live with Larry 24 mins
Daily Leetcode #1204: Jul 18, 2023 - 146. LRU Cache
YouTube video 'Leetcode 146: LRU Cache in Telugu | HashMap + Doubly LinkedList | Python DSA | srkcodes'
Srk Codes 15 mins
Leetcode 146: LRU Cache in Telugu | HashMap + Doubly LinkedList | Python DSA | srkcodes
YouTube video 'Microsoft Coding Interview Question | Leetcode 146 | LRU Cache'
WorkWithGoogler 18 mins
Microsoft Coding Interview Question | Leetcode 146 | LRU Cache
YouTube video 'Leetcode | Medium | 146. LRU Cache | Data Structure | Javascript'
Software Interviews Prep 14 mins
Leetcode | Medium | 146. LRU Cache | Data Structure | Javascript
YouTube video 'LRU Cache - LeetCode #146 - C++'
Sean Chuah 10 mins
LRU Cache - LeetCode #146 - C++
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

3 easy 4 medium
8 solutions   September 2, 2023

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