LRU Cache

T: O(1) get/put
Feedback

LRU Cache

Cache initialized
Capacity: 3 | Used: 0 | Op: 0/9
Doubly Linked List (MRU → LRU)
HEADemptyTAIL
HashMap
empty
Cache initialized
put(1,10)
put(2,20)
put(3,30)
get(2)
put(4,40)
get(1)
put(5,50)
get(3)
get(4)
SpeedNormal (500ms)
Parameters

{ capacity: number, operations: [{type:"get"|"put", key, value?}] }

Variables
capacity3
size0
opIndex0
currentOpput(1,10)
1class LRUCache(capacity):
2 map = HashMap
3 list = DoublyLinkedList
4
5 function get(key):
6 if key not in map: return -1
7 move node to front of list
8 return node.value
9
10 function put(key, value):
11 if key in map:
12 update value, move to front
13 else:
14 if size >= capacity:
15 evict tail node
16 insert new node at front
17 map[key] = new node
Output
Cache initialized