LRU Cache

Medium Design AI round

LRUCache(capacity) is a cache that holds at most capacity pairs, each a whole-number key and the whole-number value stored under it. When it is full and a new key arrives, it makes room by dropping the pair that has gone unused the longest.

get(key) returns the value stored under key, or -1 when the key is not in the cache. Reading a key counts as using it.

put(key, value) stores value under key, in place of the value already there when the key is in the cache, and counts as using the key. When that leaves more than capacity pairs in the cache, the pair whose key was used longest ago is dropped.

A key that was dropped is gone: get answers -1 for it until it is put again.

Example 1

Calls:
LRUCache(3)
put(5, 50)
put(6, 60)
put(7, 70)
get(5) → 50
put(8, 80)
get(6) → -1
get(7) → 70
get(8) → 80

Reading 5 makes it the newest, so 6 has gone unused the longest and is the pair dropped when 8 arrives.

Example 2

Calls:
LRUCache(2)
put(1, 10)
put(2, 20)
put(1, 11)
put(3, 30)
get(2) → -1
get(1) → 11
get(3) → 30

Example 3

Calls:
LRUCache(1)
get(4) → -1
put(4, 0)
get(4) → 0
put(9, 9)
get(4) → -1
get(9) → 9

Constraints

  • 1 ≤ capacity ≤ 10⁵
  • 0 ≤ key ≤ 10⁹ and 0 ≤ value ≤ 10⁹
  • at most 10⁵ calls in all to get and put

More Design

  • Min StackAI round · Medium
  • Time Based Key-Value StoreAI round · Medium
  • Find Median from Data StreamHard
  • Serialize and Deserialize Binary TreeHard
  • Insert Delete GetRandom O(1)Medium
All Design problems