← Coding round practice

LRU Cache

MediumApp Logic (real-world)

The problem

Design a Least-Recently-Used cache with O(1)-ish get and put — the pattern behind an app's image/data cache. The example runs put/get operations on a capacity-2 cache and prints the get results.

Sample input

capacity = 2; put(1,1) put(2,2) get(1) put(3,3) get(2) put(4,4) get(1) get(3) get(4)

Sample output

1 -1 -1 3 4
Show the solution · 8 languages
class LRUCache(private val capacity: Int) : LinkedHashMap<Int, Int>(capacity, 0.75f, true) {
    fun getOr(key: Int): Int = super.getOrDefault(key, -1)
    override fun removeEldestEntry(eldest: Map.Entry<Int, Int>): Boolean = size > capacity
}

fun main() {
    val lru = LRUCache(2)
    lru.put(1, 1)
    lru.put(2, 2)
    val out = StringBuilder()
    out.append(lru.getOr(1))
    lru.put(3, 3)
    out.append(" ").append(lru.getOr(2))
    lru.put(4, 4)
    out.append(" ").append(lru.getOr(1))
    out.append(" ").append(lru.getOr(3))
    out.append(" ").append(lru.getOr(4))
    println(out.toString())
}