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-1and 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
- Declare the class
LRUCache. - Add the constructor
__init__(self, capacity). Python calls it when the object is created. - Save the capacity in
self.capacity, since every laterputmust know when the cache is full. - Create
self.mapas an empty dictionary for the values. - Create
self.orderas an empty list for the recency order. - Add
get(self, key). - Handle a miss first: if the key is not in
self.map, return-1and leave the order alone. - On a hit, take the key out of
self.orderwithremove. - Append it again at the end, so it becomes the most recently used.
- Return the stored value from
self.map. - Add
put(self, key, value). - Handle an update: if the key is already stored, remove it from
order. The last line ofputappends it again, and no room is needed because the number of entries does not change. - Handle a full cache in an
elif: a new key arrives while the map already holds at leastself.capacityentries. - Pop the front key with
pop(0)and keep it inevict. That is the least recently used key. - Delete it from the map with
del. Removing it from the list alone would leave its value behind and the structures would disagree. - Store the value under the key, below the whole
ifchain, because everyputdoes this, whether the key is new or not. - Append the key to
orderas 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 tox. It raisesValueErrorwhen the value is missing, which is whygetchecks the map first andputremoves 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.mapandkey not in self.maptest the dictionary's keys, not its values.del self.map[evict]removes one entry and raisesKeyErrorif the key is absent. Becauseorderandmaphold the same keys, it is always present here.- The one-line
ifinget(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
getdoes 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 becauseget(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 afterwardsorderis[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 inself.mapuntil it is deleted, andgetwould keep returning the evicted value. - Misses must change nothing. A
getfor an unknown key such as 9 returns-1without touchingorder. - Capacity 1. Every new key evicts the previous one: after
put(1, 100)andput(2, 200),get(1)is-1andget(2)is200. - Capacity 0. The lesson does not use it. With this solution, the first
putwould callpop(0)on an empty list and raiseIndexError.
Testing
With capacity 2, here is the state of the cache after each call, taken from running the solution:
| Call | Result | order 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.
