Skip to content
Decoder

LRU Cache

Medium

Problem

Design a class LRUCache that holds at most capacity key-value pairs and, when it is full, throws out the least recently used key.

- LRUCache(capacity) creates an empty cache. - get(key) returns the value for key, or -1 if it is not there. A successful get counts as using the key. - put(key, value) inserts or updates the key, which also counts as using it. If this adds a new key and the cache is already full, first remove the key that was used longest ago.

Both get and put must run in O(1) average time.

Example 1

cache = LRUCache(2)

Example 2

put(1, 1); put(2, 2)

Example 3

Input
get(1)
Output
1
Why
1 is now the most recent

Example 4

put(3, 3)            (full: evicts 2, the least recent)

Example 5

Input
get(2)
Output
-1

Example 6

put(4, 4)            (evicts 1)

Example 7

Input
get(1)
Output
-1

Example 8

Input
get(3)
Output
3

Example 9

Input
get(4)
Output
4

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • At most 2 * 10^5 calls to get and put.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.