Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in Scala: A Mutable Map plus an ArrayBuffer

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 val capacity: Int (declared in the class header), a mutable Map[Int, Int] called map (key to value) and an ArrayBuffer[Int] called order (the keys, least recently used first).

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

Methods and rules:

  • def 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.
  • def put(key: Int, value: Int): Unit 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 primary constructor is the class header: class LRUCache(private val capacity: Int). The fields are scala.collection.mutable.Map() and scala.collection.mutable.ArrayBuffer().
  • map.contains(key) tells whether a key is stored; map(key) = value stores or replaces a value; map.remove(key) deletes an entry; map.size counts the entries.
  • order -= key removes an item by value, order += key adds at the end, and order(0) with order.remove(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 {
    def mainFunction(): Unit = {
        val c = LRUCache(2)
        c.put(1, 10)
        c.put(2, 20)
        println("Get 1: " + c.get(1))
        c.put(3, 30)
        println("Get 2: " + c.get(2))
        println("Get 3: " + c.get(3))
        println("Miss 9: " + c.get(9))
        c.put(1, 11)
        println("Update 1: " + c.get(1))
        c.put(4, 40)
        println("Evicted 3: " + c.get(3))
        println("Kept 1: " + c.get(1))
        println("Kept 4: " + c.get(4))
        val s = LRUCache(1)
        s.put(1, 100)
        s.put(2, 200)
        println("Small 1: " + s.get(1))
        println("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 -= key then order += key moves a key to the end. order(0) is the least recently used key.

class LRUCache(private val capacity: Int) {
    private val map: scala.collection.mutable.Map[Int, Int] = scala.collection.mutable.Map()
    private val order: scala.collection.mutable.ArrayBuffer[Int] = scala.collection.mutable.ArrayBuffer()

    def get(key: Int): Int = {
        if (!map.contains(key)) return -1
        order -= key
        order += key
        return map(key)
    }

    def put(key: Int, value: Int): Unit = {
        if (map.contains(key)) {
            order -= key
        } else if (map.size >= capacity) {
            val evict = order(0)
            order.remove(0)
            map.remove(evict)
        }
        map(key) = value
        order += key
    }
}

STEP 1 OF 16
    Ctrl + Enter to check

    SCALA · HASH TABLE

    Lru Cache in Scala, explained

    Problem overview

    A cache keeps a few recent results close at hand, but it can hold only a limited number of entries. When it is full and a new key arrives, it must drop one. An LRU (Least Recently Used) cache drops the entry that was used longest ago. The lesson asks for a class LRUCache that stores Int keys with Int values:

    • LRUCache(capacity) makes an empty cache that holds at most capacity entries.
    • get(key) returns the stored value, or -1 if the key isn't there. A hit counts as a use. A miss changes nothing.
    • put(key, value) stores the value and makes the key the most recently used. If the key is new and the cache is full, the least recently used entry is evicted first. If the key already exists, its value is replaced and nothing is evicted.

    The class keeps two fields: a mutable Map[Int, Int] called map and an ArrayBuffer[Int] called order that lists the keys, least recently used first.

    Approach

    Two questions must be answered quickly: "what is the value for this key?" and "which key was used longest ago?". One structure answers each. The map answers the first. The buffer answers the second by position: the front is the least recently used key and the end is the most recently used. The two must always hold the same keys.

    Every use moves a key to the end of order: remove it from wherever it is, then add it at the end. Eviction is then simple, because the key at position 0 is the one to remove, from both order and map.

    This version scans order to find a key, so each operation takes time proportional to the number of entries. That is fine for learning. A map combined with a doubly linked list reaches constant time for both operations.

    Step by step

    1. Declare the class with class LRUCache(private val capacity: Int). Putting private val in the header makes the parameter a field in the same place.
    2. Add map, a private val of type scala.collection.mutable.Map[Int, Int], starting empty. The full name matters: Scala's plain Map can't be changed.
    3. Add order, a private val scala.collection.mutable.ArrayBuffer[Int], starting empty.
    4. Start get. It takes an Int key and returns an Int.
    5. Handle a miss. If the map doesn't contain the key, return -1 before touching anything else.
    6. Take the key out of order with order -= key, which removes the item equal to the key.
    7. Add it again at the end with order += key. The key is now the most recently used.
    8. Return map(key), the stored value.
    9. Start put. It takes key and value and returns Unit.
    10. Handle an update. If the map already contains the key, remove the key from order. It will be added back at the end later, and nothing needs evicting.
    11. Handle a full cache. In an else if, test whether map.size >= capacity. This branch runs only for a new key.
    12. Read the oldest key into val evict = order(0).
    13. Remove position 0 from order with order.remove(0).
    14. Remove evict from the map with map.remove(evict). Taking it out of order alone would leave its value behind.
    15. Store the value with map(key) = value, after the whole if chain, because every put does it.
    16. Add the key at the end of order. Every put makes its key the most recently used.

    The solution in Scala

    class LRUCache(private val capacity: Int) {
        private val map: scala.collection.mutable.Map[Int, Int] = scala.collection.mutable.Map()
        private val order: scala.collection.mutable.ArrayBuffer[Int] = scala.collection.mutable.ArrayBuffer()
    
        def get(key: Int): Int = {
            if (!map.contains(key)) return -1
            order -= key
            order += key
            return map(key)
        }
    
        def put(key: Int, value: Int): Unit = {
            if (map.contains(key)) {
                order -= key
            } else if (map.size >= capacity) {
                val evict = order(0)
                order.remove(0)
                map.remove(evict)
            }
            map(key) = value
            order += key
        }
    }
    
    class Solution {
        def mainFunction(): Unit = {
            val c = LRUCache(2)
            c.put(1, 10)
            c.put(2, 20)
            println("Get 1: " + c.get(1))
            c.put(3, 30)
            println("Get 2: " + c.get(2))
            println("Get 3: " + c.get(3))
            println("Miss 9: " + c.get(9))
            c.put(1, 11)
            println("Update 1: " + c.get(1))
            c.put(4, 40)
            println("Evicted 3: " + c.get(3))
            println("Kept 1: " + c.get(1))
            println("Kept 4: " + c.get(4))
            val s = LRUCache(1)
            s.put(1, 100)
            s.put(2, 200)
            println("Small 1: " + s.get(1))
            println("Small 2: " + s.get(2))
        }
    }
    

    The Solution class at the end of that block is the lesson's test code: it builds caches and prints what get returns. Its first cache has capacity 2. Tracing that sequence, with order and the map's entries after each call:

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

    When put(3, 30) arrives, key 1 was just read, so key 2 is at the front of order and is evicted. That is why get(2) returns -1. Likewise, put(4, 40) evicts key 3.

    The Scala details worth knowing:

    • The two -= and += forms. On an ArrayBuffer, order -= key removes the first item equal to key, and order += key appends at the end. Both change the buffer in place.
    • remove(0) takes a position. order.remove(0) removes the item at index 0. This is different from -=, which takes a value. With Int items the two look alike, so keep them apart: order -= 0 would remove the key 0, not the first item.
    • Map update syntax. map(key) = value calls the map's update method: it adds the key or replaces its value. map(key) on its own reads a value and throws if the key is missing, which is why get checks map.contains(key) first.
    • map.remove(evict) returns an Option holding the old value. The lesson ignores it, and that is fine.
    • Early return. if (!map.contains(key)) return -1 leaves the method straight away. Everywhere else the last expression would do, and the lesson writes return there too.
    • The class header. private val capacity in the parameter list creates a private field. Without val, a constructor parameter used inside methods also becomes a field, but private val says so openly.

    Complexity

    Time: O(n) per operation, where n is the number of entries, at most capacity. The map lookups are fast on average. The cost comes from order: order -= key scans the buffer to find the key, and order.remove(0) shifts every remaining item one place to the left.

    Space: O(capacity). The map and the buffer each hold at most capacity keys.

    Edge cases and common mistakes

    • Updating a key must not evict. With capacity 2, after put(1, 1), put(2, 2), put(1, 5) and put(3, 3), key 1 reads 5, key 2 is gone, and key 3 reads 3. The update refreshed key 1, so key 2 was the oldest when key 3 arrived.
    • A miss changes nothing. get(9) on a cache without key 9 returns -1 and leaves order as it was.
    • Forgetting to refresh on get. Without the remove-and-append in get, reading a key wouldn't protect it, and the wrong entry would be evicted.
    • Evicting from only one structure. Removing the key from order but not from map (or the other way round) leaves the two out of step, and map.size would then give a wrong answer for "is the cache full?".
    • Capacity 1. Each 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 doesn't cover it. With this solution, put on a cache of capacity 0 finds the map "full" while order is empty, so order(0) throws an IndexOutOfBoundsException.

    Testing

    SequenceResult
    capacity 2: put(1,10), put(2,20), get(1), put(3,30), get(2), get(3)10, then -1, then 30
    then put(1,11), get(1), put(4,40), get(3), get(1), get(4)11, then -1, 11, 40
    capacity 1: put(1,100), put(2,200), get(1), get(2)-1, then 200
    capacity 2: put(1,1), put(2,2), put(1,5), put(3,3), then get(1), get(2), get(3)5, -1, 3
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free