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-1if 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>calledmapthat stores each key's value; - a
MutableList<Int>calledorderthat 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
- Declare the class with the capacity in the header:
class LRUCache(private val capacity: Int). Writingprivate valin the primary constructor creates the field and sets it in one go. - Add
map, an emptymutableMapOf()typedMutableMap<Int, Int>. - Add
order, an emptymutableListOf()typedMutableList<Int>. - Start
get. If the map doesn't contain the key, return-1immediately. A miss changes nothing, soorderstays untouched. - Refresh the key on a hit. Remove it from
orderand add it again at the end. It was somewhere in the middle; now it is the most recently used. - Return the stored value from the map.
- Start
putwith the update case. If the map already holds the key, take it out oforder. No room is needed, so nothing is evicted. - Add the eviction case as an
else if: the key is new and the map's size is already at leastcapacity. Read the first key oforderintoevict, remove position 0 fromorder, and removeevictfrom the map. Dropping it from only one structure would leave the two out of step. - Store the value with
map[key] = valuebelow the wholeifchain, so it runs for updates and new keys alike. - 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
removeagainstremoveAt. On aMutableList<Int>,remove(x)deletes the first element equal toxand returns whether it found one, whileremoveAt(i)deletes the element at positioni. WithmutableListOf(10, 20, 30),remove(1)returnsfalseand leaves the list alone, andremoveAt(1)removes20. The lesson needs both:remove(key)to take out a key by value, andremoveAt(0)to take out the first position.map[key]!!. Reading a map with[]gives anInt?, because the key might be missing (mutableMapOf(1 to 2)[9]isnull). ThecontainsKeycheck at the top ofgetguarantees the key is there, so!!turns the nullable value into a plainInt.map[key] = valueis the indexing form ofput. It inserts a new key or replaces the value of an existing one.- Properties in the header.
private val capacityis 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 andget(1)would fail. - Evicting on an update. A key already in the cache needs no room. The
else ifkeeps the eviction for new keys only. With capacity 2 holding keys 1 and 2,put(1, 5)thenput(3, 3)evicts key 2, and key 1 keeps its new value 5. - Removing from only one structure. If the evicted key leaves
orderbut notmap, the map grows past the capacity andgetstill returns the stale value. - Using
removeAt(key)where you meanremove(key). It treats the key as a position, which is the wrong element or an exception. - Misses must be silent.
getfor an unknown or evicted key returns-1and doesn't changeorderormap. - Capacity 0. The lesson doesn't use it, and this code doesn't handle it:
putwould readorder[0]from an empty list and throw anIndexOutOfBoundsException.
