Problem overview
An LRU (Least Recently Used) cache holds a limited number of entries. When it is full and a new key arrives, it throws away the entry that was used longest ago. The lesson asks for a class LRUCache that maps integer keys to integer values, built from three pieces of state:
capacity, the most entries the cache may hold;map, a[Int: Int]dictionary from key to value;order, an[Int]array of keys with the least recently used first and the most recently used last.
The class has an initializer init(_ capacity: Int) and two methods. get(_ key: Int) -> Int returns the stored value and counts as a use, or returns -1 and changes nothing when the key is absent. put(_ key: Int, _ value: Int) stores a value and makes the key the most recently used. Replacing the value of an existing key never evicts anything. Adding a new key to a full cache evicts the least recently used key first.
Take the lesson's test with capacity 2. After put(1, 10) and put(2, 20), order is [1, 2]. Reading key 1 moves it to the end, giving [2, 1]. Now put(3, 30) finds the cache full and evicts the front key, 2, so order becomes [1, 3]. That is why get(2) prints -1 while get(1) still works.
Approach: two structures that always agree
The dictionary answers "is this key here, and what is its value?" quickly. It knows nothing about time, though. The array records time: a key's position says when it was last used, and the front is always the next one to evict. Each structure covers what the other lacks, so every operation must update both, and they must hold exactly the same keys. If a key is evicted from order but left in map, get would keep finding it.
Moving a key to the "most recent" end takes two moves: remove it from wherever it sits in order, then append it. This version scans the array for every operation, so it costs time proportional to the number of entries. That is fine for learning the rules. A faster cache replaces the array with a doubly linked list so that moving a key takes constant time, and this lesson only prepares the ground for it.
Step by step
- Declare the class and keep its closing brace in place; everything else goes inside.
- Add
capacityas a privateInt. The initializer will set it. - Add
map, a private dictionary that starts empty and holds each key's value. - Add
order, a private array that starts empty and holds the keys by recency. - Write the initializer with an underscore label so callers write
LRUCache(2)instead ofLRUCache(capacity: 2). - Save the capacity with
self.capacity = capacity. Theself.tells the field from the parameter of the same name. - Start
getwith the same underscore-label style, takingkeyand returning anInt. - Handle a miss first: if
map[key]isnil, return-1straight away. A miss touches nothing, not evenorder. - On a hit, refresh the key: remove it from
orderwithremoveAll { $0 == key }, then append it at the end. - Return the value from the map. The subscript gives an optional, and the miss check above is what makes the
!safe. - Start
putwith the key and the value, both unlabeled. - Update case: if the key is already stored, take it out of
orderso that it can be re-added at the end. Nothing is evicted, because the number of entries doesn't change. - Full-cache case: in an
else if, checkmap.count >= capacity. Only a new key reaches this test, since the first branch caught every existing one. - Evict: read
order[0]intoevict, remove position 0 fromorder, and remove that key frommap. Removing it from only one of them would break the agreement between the two. - Store the value under the key and append the key to
order. These two lines come after the wholeifchain because everyputdoes them, new key or update.
The solution in Swift
class LRUCache {
private var capacity: Int
private var map: [Int: Int] = [:]
private var order: [Int] = []
init(_ capacity: Int) {
self.capacity = capacity
}
func get(_ key: Int) -> Int {
if map[key] == nil {
return -1
}
order.removeAll { $0 == key }
order.append(key)
return map[key]!
}
func put(_ key: Int, _ value: Int) {
if map[key] != nil {
order.removeAll { $0 == key }
} else if map.count >= capacity {
let evict = order[0]
order.remove(at: 0)
map.removeValue(forKey: evict)
}
map[key] = value
order.append(key)
}
}
class Solution {
func mainFunction() {
let c = LRUCache(2)
c.put(1, 10)
c.put(2, 20)
print("Get 1: \(c.get(1))")
c.put(3, 30)
print("Get 2: \(c.get(2))")
print("Get 3: \(c.get(3))")
print("Miss 9: \(c.get(9))")
c.put(1, 11)
print("Update 1: \(c.get(1))")
c.put(4, 40)
print("Evicted 3: \(c.get(3))")
print("Kept 1: \(c.get(1))")
print("Kept 4: \(c.get(4))")
let s = LRUCache(1)
s.put(1, 100)
s.put(2, 200)
print("Small 1: \(s.get(1))")
print("Small 2: \(s.get(2))")
}
}
The Solution class at the bottom is the lesson's test code, which creates caches and prints what get returns. The cache itself is the LRUCache class above it.
Swift details worth a closer look:
- Dictionary subscripts return optionals.
map[key]has typeInt?:nilfor a missing key, the value otherwise. That is whymap[key] == nilworks as a membership test, and whygetends withmap[key]!. Force-unwrapping anilwould crash the program, but here the earlier check rules that out. - Assigning through the subscript,
map[key] = value, adds a new entry or replaces the existing one. Assigningnilwould delete the entry. - The trailing closure.
removeAll { $0 == key }passes a closure toremoveAll(where:).$0is the element being tested, and every element for which the closure returnstrueis removed. The closure useskeyfrom the surrounding function. removeValue(forKey:)returns the removed value as an optional. It is marked as safe to ignore, so calling it as a statement compiles without a warning.- Classes are reference types. The test does
let c = LRUCache(2)and then callsputon it. Aletreference to a class still allows its methods to change itsvarfields. For a struct, those methods would need to be markedmutatingand the instance declared withvar. - Private fields. Code outside the class can't read or write
capacity,mapororder, so the two structures can only be changed together, throughgetandput.
Complexity
With n entries in the cache, get and put each take O(n) time. The dictionary operations are constant on average, but removeAll walks the whole array, and removing the first item with remove(at: 0) shifts every other item one place to the left. The cache needs O(capacity) space for the dictionary and the array.
Edge cases and common mistakes
- A miss must not reorder anything. Refreshing the key before checking that it exists would put a missing key into
order. - Updating a full cache must not evict. With capacity 2, after
put(1, 1)andput(2, 2), the callput(1, 5)leaves both keys in place and turnsorderinto[2, 1]. Thenget(1)returns 5 andget(2)returns 2. Testingmap.count >= capacitybefore checking whether the key exists would wrongly evict key 2. - Forgetting to remove the old position. Appending a key without first removing it leaves two copies in
order. Later, the stale front copy would be evicted even though the key was used recently. - Evicting from only one structure. Remove the evicted key from both
orderandmap. - Capacity 0. The class is written for a capacity of at least 1. With capacity 0, the first
putreadsorder[0]on an empty array and crashes.
Testing
The lesson's test with capacity 1 is a good small case: after put(1, 100) and put(2, 200), get(1) returns -1 and get(2) returns 200, because the second key evicted the first. For the capacity-2 test, the complete output is:
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
Try it in the editor above, and print order from inside the class while you experiment to watch the keys move.
