Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in Kotlin: A Map Plus a Usage 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 val capacity: Int (declared in the class header), a MutableMap<Int, Int> called map (key to value) and a MutableList<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:

  • fun 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.
  • fun 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 primary constructor is the class header: class LRUCache(private val capacity: Int). The fields are mutableMapOf() and mutableListOf().
  • map.containsKey(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.remove(key) removes an item by value (the list holds Int), order.add(key) adds at the end, and order[0] with order.removeAt(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 {
    fun mainFunction() {
        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.remove(key) then order.add(key) moves a key to the end. order[0] is the least recently used key.

class LRUCache(private val capacity: Int) {
    private val map: MutableMap<Int, Int> = mutableMapOf()
    private val order: MutableList<Int> = mutableListOf()

    fun get(key: Int): Int {
        if (!map.containsKey(key)) return -1
        order.remove(key)
        order.add(key)
        return map[key]!!
    }

    fun put(key: Int, value: Int) {
        if (map.containsKey(key)) {
            order.remove(key)
        } else if (map.size >= capacity) {
            val evict = order[0]
            order.removeAt(0)
            map.remove(evict)
        }
        map[key] = value
        order.add(key)
    }
}

STEP 1 OF 16
    Ctrl + Enter to check

    KOTLIN · HASH TABLE

    Lru Cache in Kotlin, explained

    Problem overview

    A cache holds a limited number of recent results so they are quick to read again. When it is full and a new entry arrives, it has to throw something away. An LRU (Least Recently Used) cache throws away the entry that was used longest ago.

    You write a class LRUCache that maps Int keys to Int values. It is created with a capacity and has two operations:

    • get(key) returns the stored value, or -1 if the key is not in the cache. A hit counts as a use.
    • put(key, value) stores a value. A new key in a full cache first evicts the least recently used entry. An existing key just gets a new value and nothing is evicted.

    Take the lesson's example with capacity 2. After put(1, 10) and put(2, 20), reading key 1 makes it the most recently used. Then put(3, 30) needs room, so it evicts key 2, the one used longest ago. That is why get(2) prints -1 afterwards while get(1) and get(3) still work. With capacity 1, the second put evicts the first key at once.

    Approach

    Two questions must be answered quickly: "what is the value for this key?" and "which key was used longest ago?". One structure for each:

    • a MutableMap<Int, Int> called map that stores each key's value;
    • a MutableList<Int> called order that holds the same keys, least recently used first and most recently used last.

    Every use moves a key to the end of order. The key to evict is then always order[0]. The two structures must hold exactly the same keys at all times: every change to one is paired with a change to the other.

    This version scans the list when it removes a key, so each operation takes time proportional to the number of entries. That is fine for learning and for small caches. Solutions that need constant time per operation replace the list with a linked list that can unlink a node directly; this lesson sticks to the simple list.

    Step by step

    1. Declare the class with the capacity in the header: class LRUCache(private val capacity: Int). Writing private val in the primary constructor creates the field and sets it in one go.
    2. Add map, an empty mutableMapOf() typed MutableMap<Int, Int>.
    3. Add order, an empty mutableListOf() typed MutableList<Int>.
    4. Start get. If the map doesn't contain the key, return -1 immediately. A miss changes nothing, so order stays untouched.
    5. Refresh the key on a hit. Remove it from order and add it again at the end. It was somewhere in the middle; now it is the most recently used.
    6. Return the stored value from the map.
    7. Start put with the update case. If the map already holds the key, take it out of order. No room is needed, so nothing is evicted.
    8. Add the eviction case as an else if: the key is new and the map's size is already at least capacity. Read the first key of order into evict, remove position 0 from order, and remove evict from the map. Dropping it from only one structure would leave the two out of step.
    9. Store the value with map[key] = value below the whole if chain, so it runs for updates and new keys alike.
    10. Add the key at the end of order. A put is a use, so the key becomes the most recently used.

    The solution in Kotlin

    class LRUCache(private val capacity: Int) {
        private val map: MutableMap<Int, Int> = mutableMapOf()
        private val order: MutableList<Int> = mutableListOf()
    
        fun get(key: Int): Int {
            if (!map.containsKey(key)) return -1
            order.remove(key)
            order.add(key)
            return map[key]!!
        }
    
        fun put(key: Int, value: Int) {
            if (map.containsKey(key)) {
                order.remove(key)
            } else if (map.size >= capacity) {
                val evict = order[0]
                order.removeAt(0)
                map.remove(evict)
            }
            map[key] = value
            order.add(key)
        }
    }
    
    class Solution {
        fun mainFunction() {
            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))
        }
    }
    

    Running that test code 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
    

    Kotlin details worth knowing

    • remove against removeAt. On a MutableList<Int>, remove(x) deletes the first element equal to x and returns whether it found one, while removeAt(i) deletes the element at position i. With mutableListOf(10, 20, 30), remove(1) returns false and leaves the list alone, and removeAt(1) removes 20. The lesson needs both: remove(key) to take out a key by value, and removeAt(0) to take out the first position.
    • map[key]!!. Reading a map with [] gives an Int?, because the key might be missing (mutableMapOf(1 to 2)[9] is null). The containsKey check at the top of get guarantees the key is there, so !! turns the nullable value into a plain Int.
    • map[key] = value is the indexing form of put. It inserts a new key or replaces the value of an existing one.
    • Properties in the header. private val capacity is visible inside the class only, and there's no need for a separate field and assignment.

    Complexity

    Map lookups, insertions and removals take constant time on average. The list is the slow part: order.remove(key) searches for the key, so it takes O(n) time for a cache with n entries, and removeAt(0) shifts the remaining elements, also O(n). Both get and put are therefore O(n). The space is O(capacity) for the map and the list together.

    Edge cases and common mistakes

    • Forgetting to refresh on get. If a hit doesn't move the key to the end, the cache evicts a key that was just read. In the example, get(2) would wrongly succeed and get(1) would fail.
    • Evicting on an update. A key already in the cache needs no room. The else if keeps the eviction for new keys only. With capacity 2 holding keys 1 and 2, put(1, 5) then put(3, 3) evicts key 2, and key 1 keeps its new value 5.
    • Removing from only one structure. If the evicted key leaves order but not map, the map grows past the capacity and get still returns the stale value.
    • Using removeAt(key) where you mean remove(key). It treats the key as a position, which is the wrong element or an exception.
    • Misses must be silent. get for an unknown or evicted key returns -1 and doesn't change order or map.
    • Capacity 0. The lesson doesn't use it, and this code doesn't handle it: put would read order[0] from an empty list and throw an IndexOutOfBoundsException.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free