Start learning free

LESSON 370 OF 673 · HASH TABLE

LRU Cache in Python: a Dictionary Plus a Recency List

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: self.capacity, a dictionary self.map (key to value) and a list self.order (the keys, least recently used first).

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

Methods and rules:

  • get(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.
  • put(key, 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:

  • In the constructor __init__(self, capacity), save the capacity and create self.map = {} and self.order = [].
  • key in self.map tells whether a key is stored; self.map[key] = value stores or replaces a value; del self.map[key] deletes an entry.
  • self.order.remove(key) removes an item by value, self.order.append(key) adds at the end, and self.order.pop(0) removes and returns 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):

c = LRUCache(2)
c.put(1, 10)
c.put(2, 20)
print("Get 1: " + str(c.get(1)))
c.put(3, 30)
print("Get 2: " + str(c.get(2)))
print("Get 3: " + str(c.get(3)))
print("Miss 9: " + str(c.get(9)))
c.put(1, 11)
print("Update 1: " + str(c.get(1)))
c.put(4, 40)
print("Evicted 3: " + str(c.get(3)))
print("Kept 1: " + str(c.get(1)))
print("Kept 4: " + str(c.get(4)))
s = LRUCache(1)
s.put(1, 100)
s.put(2, 200)
print("Small 1: " + str(s.get(1)))
print("Small 2: " + str(s.get(2)))

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.

self.order.remove(key) then self.order.append(key) moves a key to the end. self.order.pop(0) gives the least recently used key.

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.map = {}
        self.order = []

    def get(self, key):
        if key not in self.map: return -1
        self.order.remove(key)
        self.order.append(key)
        return self.map[key]

    def put(self, key, value):
        if key in self.map:
            self.order.remove(key)
        elif len(self.map) >= self.capacity:
            evict = self.order.pop(0)
            del self.map[evict]
        self.map[key] = value
        self.order.append(key)

STEP 1 OF 17
    Ctrl + Enter to check

    PYTHON · HASH TABLE

    Lru Cache in Python, explained

    Problem overview

    A cache holds a limited number of entries. When it is full and a new key arrives, something has to go. An LRU (least recently used) cache evicts the entry that was used longest ago. The class LRUCache stores integer keys with integer values and offers two operations:

    • get(key) returns the stored value and makes the key the most recently used. A missing key returns -1 and changes nothing.
    • put(key, value) stores the value and makes the key the most recently used. Updating an existing key never evicts anything. Adding a new key to a full cache first evicts the least recently used entry.

    The class keeps three fields: self.capacity, a dictionary self.map from key to value, and a list self.order with the keys sorted by use, the least recently used at the front and the most recently used at the end.

    Approach: two structures that always agree

    The dictionary answers "is this key stored, and what is its value?" in constant time on average. It says nothing about recency, because the dictionary is not what tells you which key is oldest. That job belongs to the list: a key's position in order is its rank by use. The two structures must always hold exactly the same keys, so every operation that touches one has to update the other.

    Take a cache with capacity 2. After put(1, 10) and put(2, 20), order is [1, 2]. Calling get(1) returns 10 and moves 1 to the end, giving [2, 1]. Now put(3, 30) arrives and the cache is full, so the front key, 2, is evicted. The map becomes {1: 10, 3: 30} and order becomes [1, 3]. A later get(2) returns -1.

    Moving a key to the end is the same two list calls every time: remove(key) takes it out wherever it is, and append(key) puts it back at the right end. This version scans the list for those calls, so each operation costs time proportional to the number of entries. That is fine for learning; the constant-time design for interviews replaces the list with a doubly linked list.

    Step by step

    1. Declare the class LRUCache.
    2. Add the constructor __init__(self, capacity). Python calls it when the object is created.
    3. Save the capacity in self.capacity, since every later put must know when the cache is full.
    4. Create self.map as an empty dictionary for the values.
    5. Create self.order as an empty list for the recency order.
    6. Add get(self, key).
    7. Handle a miss first: if the key is not in self.map, return -1 and leave the order alone.
    8. On a hit, take the key out of self.order with remove.
    9. Append it again at the end, so it becomes the most recently used.
    10. Return the stored value from self.map.
    11. Add put(self, key, value).
    12. Handle an update: if the key is already stored, remove it from order. The last line of put appends it again, and no room is needed because the number of entries does not change.
    13. Handle a full cache in an elif: a new key arrives while the map already holds at least self.capacity entries.
    14. Pop the front key with pop(0) and keep it in evict. That is the least recently used key.
    15. Delete it from the map with del. Removing it from the list alone would leave its value behind and the structures would disagree.
    16. Store the value under the key, below the whole if chain, because every put does this, whether the key is new or not.
    17. Append the key to order as the most recently used.

    The solution in Python

    class LRUCache:
        def __init__(self, capacity):
            self.capacity = capacity
            self.map = {}
            self.order = []
    
        def get(self, key):
            if key not in self.map: return -1
            self.order.remove(key)
            self.order.append(key)
            return self.map[key]
    
        def put(self, key, value):
            if key in self.map:
                self.order.remove(key)
            elif len(self.map) >= self.capacity:
                evict = self.order.pop(0)
                del self.map[evict]
            self.map[key] = value
            self.order.append(key)
    
    c = LRUCache(2)
    c.put(1, 10)
    c.put(2, 20)
    print("Get 1: " + str(c.get(1)))
    c.put(3, 30)
    print("Get 2: " + str(c.get(2)))
    print("Get 3: " + str(c.get(3)))
    print("Miss 9: " + str(c.get(9)))
    c.put(1, 11)
    print("Update 1: " + str(c.get(1)))
    c.put(4, 40)
    print("Evicted 3: " + str(c.get(3)))
    print("Kept 1: " + str(c.get(1)))
    print("Kept 4: " + str(c.get(4)))
    s = LRUCache(1)
    s.put(1, 100)
    s.put(2, 200)
    print("Small 1: " + str(s.get(1)))
    print("Small 2: " + str(s.get(2)))
    

    The code below the class is the lesson's test script. It prints:

    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
    

    The Python details worth knowing:

    • list.remove(x) deletes by value, the first item equal to x. It raises ValueError when the value is missing, which is why get checks the map first and put removes only when the key is stored.
    • list.pop(0) removes and returns the first item. pop() with no argument takes the last one, so the index matters here: the front is the oldest key.
    • key in self.map and key not in self.map test the dictionary's keys, not its values.
    • del self.map[evict] removes one entry and raises KeyError if the key is absent. Because order and map hold the same keys, it is always present here.
    • The one-line if in get (if key not in self.map: return -1) is legal Python; the longer two-line form means the same.

    Complexity

    Time: O(n) per operation, where n is the number of entries, which is at most the capacity. The dictionary lookups and the append are fast, but remove(key) scans the list to find the key, and pop(0) shifts every remaining item one place to the left. A hash map plus a doubly linked list brings get and put down to O(1).

    Space: O(capacity), because the dictionary and the list each hold at most capacity keys.

    Edge cases and common mistakes

    • Forgetting that a read is a use. If get does not move the key to the end, the cache evicts the wrong entry. In the example, key 2 is evicted rather than key 1 only because get(1) moved 1 to the back.
    • Evicting on an update. Writing a new value for a stored key must not evict anything. With capacity 2 holding keys 1 and 3, put(1, 11) keeps both, and afterwards order is [3, 1].
    • Checking capacity before checking for an update. That is why the update case comes first and the eviction is an elif.
    • Leaving the map entry behind. After pop(0), the key still sits in self.map until it is deleted, and get would keep returning the evicted value.
    • Misses must change nothing. A get for an unknown key such as 9 returns -1 without touching order.
    • Capacity 1. Every new key evicts the previous one: after put(1, 100) and put(2, 200), get(1) is -1 and get(2) is 200.
    • Capacity 0. The lesson does not use it. With this solution, the first put would call pop(0) on an empty list and raise IndexError.

    Testing

    With capacity 2, here is the state of the cache after each call, taken from running the solution:

    CallResultorder afterwards
    put(1, 10)[1]
    put(2, 20)[1, 2]
    get(1)10[2, 1]
    put(3, 30)[1, 3]
    get(2)-1[1, 3]
    get(3)30[1, 3]
    put(1, 11)[3, 1]
    put(4, 40)[1, 4]

    Key 3 is evicted by put(4, 40), because it was the least recently used after the update of key 1.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free