LRU Cache
Problem Statement
Build a class LRUCache: a keyβvalue store with a fixed size limit. When it is full and a new key arrives, it throws out the key that was used longest ago (the least recently used, "LRU").
LRUCache(int capacity)creates an empty cache that can hold at mostcapacitykeys.int get(int key)returns the value ofkey, or-1if it is not stored. A successful get counts as a use of that key.void put(int key, int value)storesvalueunderkey. If the key already exists, its value is replaced. Otherwise it is added, and if that makes the cache hold more thancapacitykeys, the least recently used key is removed first. A put also counts as a use.
Both get and put must run in O(1) average time.
The capacity, then a sequence of get(key) and put(key, value) calls.
For each get, the stored value or -1. put returns nothing.
After get(1), key 1 is the most recent, so put(3, 3) evicts key 2. Then key 1 is the oldest, so put(4, 4) evicts key 1. Keys 3 and 4 remain.
- β’ 1 β€ capacity β€ 3000
- β’ 0 β€ key β€ 10^4
- β’ 0 β€ value β€ 10^5
- β’ At most 2 Β· 10^5 calls to get and put
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Vector of (key, value) from most to least recent; linear search on every call
List keeps recency order; map key β list node; splice to front, evict from back
Keep a vector<pair<int,int>> ordered from most recently used (index 0) to least recently used (the back). get and put search the vector for the key. On a hit, erase the pair and re-insert it at the front. To evict, pop_back.
Recognition rule for this sub-pattern:
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.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.