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 mostcapacityentries.get(key)returns the stored value, or-1if 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
- Declare the class with
class LRUCache(private val capacity: Int). Puttingprivate valin the header makes the parameter a field in the same place. - Add
map, aprivate valof typescala.collection.mutable.Map[Int, Int], starting empty. The full name matters: Scala's plainMapcan't be changed. - Add
order, aprivate valscala.collection.mutable.ArrayBuffer[Int], starting empty. - Start
get. It takes anIntkey and returns anInt. - Handle a miss. If the map doesn't contain the key, return
-1before touching anything else. - Take the key out of
orderwithorder -= key, which removes the item equal to the key. - Add it again at the end with
order += key. The key is now the most recently used. - Return
map(key), the stored value. - Start
put. It takeskeyandvalueand returnsUnit. - 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. - Handle a full cache. In an
else if, test whethermap.size >= capacity. This branch runs only for a new key. - Read the oldest key into
val evict = order(0). - Remove position 0 from
orderwithorder.remove(0). - Remove
evictfrom the map withmap.remove(evict). Taking it out oforderalone would leave its value behind. - Store the value with
map(key) = value, after the wholeifchain, because every put does it. - 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:
| Call | Result | order | map |
|---|---|---|---|
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 anArrayBuffer,order -= keyremoves the first item equal tokey, andorder += keyappends 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. WithIntitems the two look alike, so keep them apart:order -= 0would remove the key 0, not the first item.- Map update syntax.
map(key) = valuecalls the map'supdatemethod: 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 whygetchecksmap.contains(key)first. map.remove(evict)returns anOptionholding the old value. The lesson ignores it, and that is fine.- Early
return.if (!map.contains(key)) return -1leaves the method straight away. Everywhere else the last expression would do, and the lesson writesreturnthere too. - The class header.
private val capacityin the parameter list creates a private field. Withoutval, a constructor parameter used inside methods also becomes a field, butprivate valsays 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)andput(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-1and leavesorderas it was. - Forgetting to refresh on
get. Without the remove-and-append inget, reading a key wouldn't protect it, and the wrong entry would be evicted. - Evicting from only one structure. Removing the key from
orderbut not frommap(or the other way round) leaves the two out of step, andmap.sizewould then give a wrong answer for "is the cache full?". - Capacity 1. Each new key evicts the previous one: after
put(1, 100)andput(2, 200),get(1)is-1andget(2)is200. - Capacity 0. The lesson doesn't cover it. With this solution,
puton a cache of capacity 0 finds the map "full" whileorderis empty, soorder(0)throws anIndexOutOfBoundsException.
Testing
| Sequence | Result |
|---|---|
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 |
