Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in Swift: 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: private var capacity: Int, a dictionary map: [Int: Int] (key to value) and an array order: [Int] (the keys, least recently used first).

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

Methods and rules:

  • func get(_ key: Int) -> Int 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.
  • func put(_ key: Int, _ value: Int) 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 initializer init(_ capacity: Int) saves the capacity; the fields start as [:] and [].
  • map[key] != nil tells whether a key is stored; map[key] = value stores or replaces a value; map.removeValue(forKey: key) deletes an entry; map.count counts the entries.
  • order.removeAll { $0 == key } removes an item by value, order.append(key) adds at the end, and order[0] with order.remove(at: 0) 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 {
    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))")
    }
}

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.removeAll { $0 == key } then order.append(key) moves a key to the end. order[0] is the least recently used key.

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

STEP 1 OF 20
    Ctrl + Enter to check

    SWIFT · HASH TABLE

    Lru Cache in Swift, explained

    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

    1. Declare the class and keep its closing brace in place; everything else goes inside.
    2. Add capacity as a private Int. The initializer will set it.
    3. Add map, a private dictionary that starts empty and holds each key's value.
    4. Add order, a private array that starts empty and holds the keys by recency.
    5. Write the initializer with an underscore label so callers write LRUCache(2) instead of LRUCache(capacity: 2).
    6. Save the capacity with self.capacity = capacity. The self. tells the field from the parameter of the same name.
    7. Start get with the same underscore-label style, taking key and returning an Int.
    8. Handle a miss first: if map[key] is nil, return -1 straight away. A miss touches nothing, not even order.
    9. On a hit, refresh the key: remove it from order with removeAll { $0 == key }, then append it at the end.
    10. Return the value from the map. The subscript gives an optional, and the miss check above is what makes the ! safe.
    11. Start put with the key and the value, both unlabeled.
    12. Update case: if the key is already stored, take it out of order so that it can be re-added at the end. Nothing is evicted, because the number of entries doesn't change.
    13. Full-cache case: in an else if, check map.count >= capacity. Only a new key reaches this test, since the first branch caught every existing one.
    14. Evict: read order[0] into evict, remove position 0 from order, and remove that key from map. Removing it from only one of them would break the agreement between the two.
    15. Store the value under the key and append the key to order. These two lines come after the whole if chain because every put does 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 type Int?: nil for a missing key, the value otherwise. That is why map[key] == nil works as a membership test, and why get ends with map[key]!. Force-unwrapping a nil would 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. Assigning nil would delete the entry.
    • The trailing closure. removeAll { $0 == key } passes a closure to removeAll(where:). $0 is the element being tested, and every element for which the closure returns true is removed. The closure uses key from 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 calls put on it. A let reference to a class still allows its methods to change its var fields. For a struct, those methods would need to be marked mutating and the instance declared with var.
    • Private fields. Code outside the class can't read or write capacity, map or order, so the two structures can only be changed together, through get and put.

    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) and put(2, 2), the call put(1, 5) leaves both keys in place and turns order into [2, 1]. Then get(1) returns 5 and get(2) returns 2. Testing map.count >= capacity before 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 order and map.
    • Capacity 0. The class is written for a capacity of at least 1. With capacity 0, the first put reads order[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.

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