Practice · Hashing · 5 of 7

Least Recently Used Cache

Write a class LRUCache, a key-value store that holds at most capacity keys:

  • LRUCache(capacity) makes an empty cache.
  • get(key) returns the value stored for key, or -1 if the cache doesn't hold it.
  • put(key, value) stores value for key, replacing any old value. If that would add a new key to a full cache, first remove the least recently used key: the one whose last get or put was longest ago.

A get that finds its key and every put count as using that key. Both methods must take constant time on average.

Each test is a list of calls, starting with the constructor; the expected answer lists what each call returns (null for the constructor and for put).

Example 1

Calls
LRUCache(2), put(1, 100), put(2, 200), get(1), put(3, 300), get(2), get(3), get(1)
Returns
[null, null, null, 100, null, -1, 300, 100]
Reading key 1 makes key 2 the least recently used, so putting key 3 evicts key 2.

Example 2

Calls
LRUCache(1), put(5, 7), put(5, 8), get(5), put(6, 9), get(5)
Returns
[null, null, null, 8, null, -1]
Putting a key that is already there replaces its value and evicts nothing.

Constraints

  • 1 ≤ capacity ≤ 3000
  • Keys are between 0 and 10⁴; values are between 0 and 10⁵.
  • A test makes at most 2 × 10⁵ calls.