backbenchcode
← all problemsnext: Median of a Data Stream
#09HardData Structures · 38% acceptance

Design an LRU Cache

DesignHash MapLinked List

Design a cache with a fixed capacity that supports get(key) and put(key, value) in O(1) average time. When full, it evicts the least-recently-used entry.

Every pipeline you have written that caches expensive results is solving a version of this. Now make it strict.

Examples

Input: capacity = 2; put(1,1); put(2,2); get(1); put(3,3); get(2)

Output: get(2) -> -1

Note: Inserting 3 evicts key 2, the least recently used.

Constraints

Hints

solution.pyPython 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Test console

// hit Run to execute the sample tests

// Interactive editor preview. Live code execution arrives with your early-access cohort.