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();
}
};
Difficulty
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
AI Disclaimer
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.
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;
Itemis a simplepairholding a key and its associated value.posmaps each key to the exact position of its node insidelru.lruholds the items ordered from most recent (front) to least recent (back).maxsizerecords 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
counttest 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
getmoves the node to the front, ensuring that subsequentputoperations 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 witherase(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, andposis refreshed to point to the new iterator.
Edge Cases Handled
- Insertion into a full cache - The eviction block runs only when
pos.size()equalsmaxsize, 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
maxsizeis zero, the conditionpos.size() == maxsizeis true on every insertion, causing immediate eviction of the newly added node. The cache therefore remains empty, and any subsequentgetwill return-1. - Repeated
putfor 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. Botherase(pos[key])andpos[key] = lru.begin()are O(1). - Doubly-linked list for ordering -
listprovides 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_mapsupplies 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 460: LFU Cache
- problem 588: Design In-Memory File System
- problem 1756: Design Most Recently Used Queue
Solved On The Same Day
- problem 563: Binary Tree Tilt
- problem 938: Range Sum of BST
- problem 965: Univalued Binary Tree
- problem 371: Sum of Two Integers
- problem 865: Smallest Subtree with all the Deepest Nodes
- problem 1201: Ugly Number III
- problem 2707: Extra Characters in a String
Extra
- 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