AlgoFrames

LRU cache

Standard · Write code · about 20 min

Simulate an LRU cache that holds up to capacity keys and starts empty. Run the commands in order:

  • get K returns the value of key K, or -1 if K is not cached. A hit makes K the most recently used key.
  • put K V stores V under K and makes K the most recently used key. If K is new and the cache is full, first evict the least recently used key.

Return the results of the get commands in order. Each command must take O(1) on average.

Example 1

Input:

[2,["put 1 1","put 2 2","get 1","put 3 3","get 2","put 4 4","get 1","get 3","get 4"]]

Output:

[1,-1,-1,3,4]

put 3 evicts 2, and put 4 evicts 1.

Example 2

Input:

[2,["put 1 1","put 1 5","get 1"]]

Output:

[5]

The second put updates key 1.

Constraints

  • 1 ≤ capacity ≤ 3,000
  • 0 ≤ commands.length ≤ 10,000
  • 0 ≤ K ≤ 10,000 and 0 ≤ V ≤ 100,000
  • Each command is get K or put K V

Learn the idea first: LRU and LFU caches, a visual lesson.

More LRU and LFU caches problems