Problem overview
A cache holds a limited number of entries. When it is full and a new key arrives, it must drop one entry to make room. An LRU (Least Recently Used) cache drops the entry that was used longest ago. The task is to write the class LRUCache for integer keys and integer values.
The class has three fields: int capacity, an unordered_map<int, int> named map from key to value, and a vector<int> named order that lists the keys from least recently used (front) to most recently used (back). It offers a constructor and two methods:
get(key)returns the stored value and makes the key the most recently used one. A missing key returns-1and changes nothing.put(key, value)stores the value and makes the key the most recently used one. Updating an existing key evicts nothing. Adding a new key to a full cache first evicts the least recently used entry.
Both reads and writes count as "use". That is why get also changes order.
Approach: a map for values, a vector for recency
Two questions need quick answers: "what value belongs to this key?" and "which key was used longest ago?". The map answers the first. The vector answers the second, because its position encodes recency: the front is the next victim, and every use moves a key to the back.
The two structures must always hold exactly the same keys. Every step of the lesson either changes both or leaves both alone, and most bugs come from updating only one of them.
This version scans order to find a key, so a get or put on an existing key costs time proportional to the number of entries. That is fine while learning. The usual faster design replaces the vector with a doubly linked list, so moving a key costs constant time.
Here is the lesson's own example with capacity 2. The order is written front to back, and each line was produced by running the solution:
put(1,10) order: 1
put(2,20) order: 1 2
get(1)=10 order: 2 1
put(3,30) order: 1 3 (key 2 was at the front, so it was evicted)
get(2)=-1 order: 1 3
get(3)=30 order: 1 3
put(1,11) order: 3 1 (update: no eviction, key 1 moves to the back)
put(4,40) order: 1 4 (key 3 was at the front, so it was evicted)
Step by step
- Declare the class and its closing
};straight away. A class definition ends with a semicolon, and forgetting it is a classic compile error. - Open the
private:part and declare the fields there, so only the cache itself can change them. - Add the three fields:
capacity,mapandorder. Both containers start empty without any extra code. - Open the
public:part for the constructor and the methods. - Write the constructor with one
intparameter. Its body saves the argument withthis->capacity = capacity. The parameter has the same name as the field, sothis->picks the field. - Start
get. A miss comes first: ifmap.find(key)equalsmap.end(), return-1and touch nothing. - On a hit, move the key to the back. Remove it from
order, thenpush_backit again, and finally returnmap[key]. - Start
putwith an update. If the key is already stored, take it out oforder. It gets pushed back at the end of the method, and no space is needed because the number of entries stays the same. - Handle a new key in a full cache with an
else if: when the number of entries is at leastcapacity, readorder.front()asevict, erase the first element oforderand erase that key from the map. Removing it from only one structure leaves them out of sync. - Store the value and the recency. After the whole
ifchain,map[key] = valueandorder.push_back(key)run for everyput, whether the key is new or updated.
The solution in C++
class LRUCache {
private:
int capacity;
unordered_map<int, int> map;
vector<int> order;
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (map.find(key) == map.end()) return -1;
order.erase(remove(order.begin(), order.end(), key), order.end());
order.push_back(key);
return map[key];
}
void put(int key, int value) {
if (map.find(key) != map.end()) {
order.erase(remove(order.begin(), order.end(), key), order.end());
} else if ((int)map.size() >= capacity) {
int evict = order.front();
order.erase(order.begin());
map.erase(evict);
}
map[key] = value;
order.push_back(key);
}
};
class Solution {
public:
void mainFunction() {
LRUCache c(2);
c.put(1, 10);
c.put(2, 20);
cout << "Get 1: " << c.get(1) << endl;
c.put(3, 30);
cout << "Get 2: " << c.get(2) << endl;
cout << "Get 3: " << c.get(3) << endl;
cout << "Miss 9: " << c.get(9) << endl;
c.put(1, 11);
cout << "Update 1: " << c.get(1) << endl;
c.put(4, 40);
cout << "Evicted 3: " << c.get(3) << endl;
cout << "Kept 1: " << c.get(1) << endl;
cout << "Kept 4: " << c.get(4) << endl;
LRUCache s(1);
s.put(1, 100);
s.put(2, 200);
cout << "Small 1: " << s.get(1) << endl;
cout << "Small 2: " << s.get(2) << endl;
}
};
The Solution class at the end is the lesson's test code, which uses the cache. The C++ details worth a closer look:
- The erase-remove idiom.
std::removedoes not shrink the vector. It shifts the elements that differ fromkeyto the front, keeping their order, and returns an iterator to the end of that kept part. The elements after it are left in an unspecified state. For{1, 2, 3, 2}and the key 2, the returned iterator points just after the first two elements, which are1, 3. The call toerase(…, order.end())then cuts off the leftover tail. Because every key appears at most once inorder, this removes exactly one element. map.findagainstmap[key].operator[]inserts a default value (0) when the key is missing. That is whygetchecks withfindfirst and only usesmap[key]once it knows the key exists. Callingmap[key]on a miss would add a phantom entry to the map but not toorder.- The cast in
(int)map.size().size()returns an unsigned type. Comparing it with the signedcapacitywould convert the signed value to unsigned, which compilers often warn about. Casting the size tointkeeps the comparison signed. - Names inside the class.
capacityin the constructor's parameter list hides the field, so the assignment needsthis->. Everywhere else in the class, the plain name means the field.
Complexity
Let k be the number of entries, at most capacity.
Time. Looking a key up in the map takes constant time on average. Finding the key in order with remove scans the whole vector, so a hit in get and an update in put cost O(k). Erasing the first element of a vector shifts every other element, so an eviction is O(k) as well. A miss in get is the only cheap case.
Space: O(k). The map and the vector each hold one item per cached key.
Edge cases and common mistakes
- A miss changes nothing.
get(9)on a cache without key 9 returns-1and leavesorderand the map as they were. - Reads count as use. In the example,
get(1)beforeput(3, 30)is what makes key 2, not key 1, the one that gets evicted. Without moving the key inget, key 1 would stay at the front and be evicted instead. - Updates don't evict.
put(1, 11)on a full cache that already holds key 1 only replaces the value. Checking the capacity before checking whether the key exists would wrongly evict another entry. - Forgetting
map.erase(evict). The key leavesorderbut its value stays in the map, so the map grows past the capacity and the next eviction test sees the wrong size. - Forgetting to remove the key before
push_back. The key would appear twice inorder, and a later eviction could remove an entry that was recently used. - Capacity 1. Every new key evicts the previous one: after
put(1, 100)andput(2, 200), key 1 is gone and key 2 holds 200.
Testing
The lesson's own program prints the following. Every line was produced by running the solution:
Get 1: 10
Get 2: -1
Get 3: 30
Miss 9: -1
Update 1: 11
Evicted 3: -1
Kept 1: 11
Kept 4: 40
Small 1: -1
Small 2: 200
