LRU Cache
franklinqin0 Hash TableLinked ListDesignDoubly-Linked List
# Driver Code
obj = LRUCache(capacity)
param_1 = obj.get(key)
obj.put(key,value)
1
2
3
2
3
# Solution
Both solutions below take constant time.
Complexity
time: (all operations)
space:
# Cheating w/ Built-in OrderDict
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.dct = OrderedDict()
def get(self, key: int) -> int:
if key not in self.dct:
return -1
# update order
self.dct.move_to_end(key, last=True)
# get from od
return self.dct[key]
def put(self, key: int, value: int) -> None:
# remove old entry if present
if key in self.dct:
self.dct.move_to_end(key, last=True)
# put in od
self.dct[key] = value
# remove lru if exceed capacity
if len(self.dct) > self.cap:
self.dct.popitem(last=False)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# HashMap & Doubly Linked List
dct is a hashmap that maps from key to ListNode, while head and tail define a doubly linked list that makes adding, moving, and removing nodes .
# Doubly Linked List node
class ListNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.dct = {} # key -> ListNode
# head and tail are sentinel nodes
self.head = ListNode(-1, -1)
self.tail = ListNode(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
def add_node(self, node): # add node to end of ll
# update tail & node
self.tail.prev.next = node
node.prev = self.tail.prev
node.next = self.tail
self.tail.prev = node
def del_node(self, node): # remove node
# if (not node.prev):
# print('oh no')
node.prev.next = node.next
node.next.prev = node.prev
node.next = None
node.prev = None
def get(self, key: int) -> int:
# if key not in hashmap, return -1
if key not in self.dct:
return -1
# find node, remove in ll, add to end
node = self.dct[key]
self.del_node(node)
self.add_node(node)
return node.val
def put(self, key: int, value: int) -> None:
# if key exists, remove from ll
if key in self.dct:
node = self.dct[key]
self.del_node(node)
# update value, add to ll
node = ListNode(key, value)
self.dct[key] = node
self.add_node(node)
# remove lru if exceeds capacity
if len(self.dct) > self.cap:
lru = self.head.next
self.del_node(lru)
del self.dct[lru.key]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59