Skip to content
DeepForgeby svx
All problems
HardData Structuresds-038

LRU Cache

Problem

Simulate a Least Recently Used (LRU) cache with the given capacity.

operations contains "put" or "get". For put, values[i] is a [key, value] pair; for get, values[i] is the key. A get returns the stored value or -1 when missing. Both get and put mark the key as most recently used, and put evicts the least recently used key when the cache exceeds capacity.

Return the list of recorded results (None for put).

Hint

An OrderedDict keeps insertion order; move_to_end marks recent use and popitem(last=False) evicts.

Test cases

case 1
in: [2,["put","put","get","put","get","get"],[[1,1],[2,2],1,[3,3],2,3]]
expected: [null,null,1,null,-1,3]
case 2
in: [1,["put","get","put","get"],[[2,1],2,[3,2],2]]
expected: [null,1,null,-1]
case 3
in: [2,["get"],[5]]
expected: [-1]
case 4
in: [1,["put","put","get"],[[1,1],[1,2],1]]
expected: [null,null,2]
Starter codePython
def lru_cache(capacity, operations, values):
    # Your code here
    pass

4 test cases · run your code against them in the editor