InferenceAI

Enter at least two characters to search.

Start free

LRU Cache Simulator

mediumDesign25 min25 XP

Simulate an LRU cache with the given capacity. Each operation is either ["put", key, value] or ["get", key].

  • get returns the value, or -1 if the key is missing, and marks the key as most recently used.
  • put inserts or updates the key and marks it most recently used. If the cache exceeds capacity, evict the least recently used key.

Return the list of results of all get operations, in order.

Requirements

  • Both operations in O(1)O(1): a hash map plus a doubly linked list (or OrderedDict).

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[2,[["put",1,1],["put",2,2],["get",1],["put",3,3],["get",2],["put",4,4],["get",1],["get",3],["get",4]]]
TASKlru_cache_simulator()
EXPECTED OUTPUT[1,-1,-1,3,4]

Start with the input values shown in this example.

Example 1 of 3

Input: capacity = 2, operations = [["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]

Explanation: classic

Input: capacity = 1, operations = [["put",1,1],["put",1,5],["get",1]]

Output: [5]

Explanation: update

Input: capacity = 1, operations = [["get",7]]

Output: [-1]

Explanation: missing key

Hint 1

An OrderedDict keeps insertion order and supports move_to_end and popitem(last=False).

Hint 2

In other languages, pair a hash map with a doubly linked list.

Topics

DSADesignPython