Start learning free

LESSON 86 OF 319 · HASH TABLE

LRU Cache in C++: unordered_map and vector Implementation

Practice Read the full explanation

A cache keeps a few recent results close at hand so they are quick to read again. It can only hold a limited number of entries, so when it is full it must throw one away. An LRU (Least Recently Used) cache throws away the entry that was used longest ago. Build a class LRUCache that stores integer keys with integer values.

The class keeps: int capacity, an unordered_map<int, int> called map (key to value) and a vector<int> called order (the keys, least recently used first).

Create it: LRUCache c(capacity) makes an empty cache that holds at most capacity entries.

Methods and rules:

  • int get(int key) returns the value stored for key. A hit counts as a use: the key becomes the most recently used. If the key is not in the cache (never stored, or already evicted), return -1 and change nothing.
  • void put(int key, int value) stores the value for key, and the key becomes the most recently used.
    • If the key is already in the cache, replace its value. Nothing is evicted.
    • If the key is new and the cache already holds capacity entries, first evict the least recently used entry (remove it from the map and from order), then store the new one.
  • Keep order sorted by use: the least recently used key at the front, the most recently used at the end. Every use moves the key to the end.

Tools for this language:

  • The constructor LRUCache(int capacity) saves the capacity with this->capacity = capacity. Put the fields in private: and the methods in public:.
  • map.find(key) != map.end() tells whether a key is stored; map[key] = value stores or replaces a value; map.erase(key) deletes an entry; map.size() counts the entries.
  • order.erase(remove(order.begin(), order.end(), key), order.end()) removes an item by value, order.push_back(key) adds at the end, and order.front() with order.erase(order.begin()) reads and removes the first item.

This version walks over the list of keys for each operation, which is fine for learning. Interview solutions reach O(1) with a hash map plus a doubly linked list.

You start with the code that tests your class (write LRUCache above it):

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;
    }
};

Expected output:

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

Check it against the rules: Get 2 is -1 because key 2 was the least recently used when key 3 arrived (key 1 had just been read). Updating key 1 to 11 does not evict anything. With capacity 1, the second put evicts the first key.


Two structures work together: the map gives a fast lookup of the value, and order remembers which key was used when. Both must always hold the same keys.

order.erase(remove(order.begin(), order.end(), key), order.end()) then order.push_back(key) moves a key to the end. order.front() is the least recently used key.

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);
    }
};

STEP 1 OF 21
    Ctrl + Enter to check

    C++ · HASH TABLE

    Lru Cache in C++, explained

    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 -1 and 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

    1. Declare the class and its closing }; straight away. A class definition ends with a semicolon, and forgetting it is a classic compile error.
    2. Open the private: part and declare the fields there, so only the cache itself can change them.
    3. Add the three fields: capacity, map and order. Both containers start empty without any extra code.
    4. Open the public: part for the constructor and the methods.
    5. Write the constructor with one int parameter. Its body saves the argument with this->capacity = capacity. The parameter has the same name as the field, so this-> picks the field.
    6. Start get. A miss comes first: if map.find(key) equals map.end(), return -1 and touch nothing.
    7. On a hit, move the key to the back. Remove it from order, then push_back it again, and finally return map[key].
    8. Start put with an update. If the key is already stored, take it out of order. It gets pushed back at the end of the method, and no space is needed because the number of entries stays the same.
    9. Handle a new key in a full cache with an else if: when the number of entries is at least capacity, read order.front() as evict, erase the first element of order and erase that key from the map. Removing it from only one structure leaves them out of sync.
    10. Store the value and the recency. After the whole if chain, map[key] = value and order.push_back(key) run for every put, 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::remove does not shrink the vector. It shifts the elements that differ from key to 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 are 1, 3. The call to erase(…, order.end()) then cuts off the leftover tail. Because every key appears at most once in order, this removes exactly one element.
    • map.find against map[key]. operator[] inserts a default value (0) when the key is missing. That is why get checks with find first and only uses map[key] once it knows the key exists. Calling map[key] on a miss would add a phantom entry to the map but not to order.
    • The cast in (int)map.size(). size() returns an unsigned type. Comparing it with the signed capacity would convert the signed value to unsigned, which compilers often warn about. Casting the size to int keeps the comparison signed.
    • Names inside the class. capacity in the constructor's parameter list hides the field, so the assignment needs this->. 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 -1 and leaves order and the map as they were.
    • Reads count as use. In the example, get(1) before put(3, 30) is what makes key 2, not key 1, the one that gets evicted. Without moving the key in get, 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 leaves order but 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 in order, 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) and put(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
    
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free