Polski

LRU cache

A fixed-capacity cache that evicts the least recently used entry when full. get and put in O(1) – a map plus a doubly linked list.

medium · typescript · javascript · python · csharp · java · go · 20 XP

A user-profile service queries a slow database, so it keeps recently read profiles in memory. Memory is limited: when space runs out, the least recently used entry goes. Both operations must be constant time – the cache sits on the hot path of every request.

Task

A class LRUCache with capacity capacity ≥ 1:

OperationBehaviour
get(key)returns the value or -1 when the key is absent; a hit makes the entry the most recent
put(key, value)inserts or updates the entry and makes it the most recent; if inserting a new key pushes the size above the capacity, evicts the least recently used entry
sizenumber of entries

Names: JS/TS LRUCache, get, put, getter size; Python LRUCache, get, put, len(cache); C# LruCache, Get, Put, Count; Java LruCache, get, put, size(); Go NewLRUCache(capacity), Get, Put, Len.

Example

Capacity 2:

OperationResultContents (least → most recently used)
put(1, 1), put(2, 2)–1, 2
get(1)12, 1
put(3, 3)–1, 3 (2 evicted)
get(2)-11, 3
put(1, 10)–3, 1
put(4, 4)–1, 4 (3 evicted)
get(1)104, 1

Constraints

  • 1 ≤ capacity ≤ 100,000, keys and values are integers 0 … 10⁹.
  • Up to 200,000 operations per test.

Expected complexity

get and put in O(1) (average), O(capacity) memory.

Topics: Proxy