forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathLRU_Cache.py
111 lines (79 loc) · 2.58 KB
/
LRU_Cache.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class LRUCache:
def __init__(self, maxSize):
self.cache = {}
self.maxSize = maxSize or 1
self.currentSize = 0
self.listOfMostRecent = DoublyLinkedList()
# O(1) time | O(1) space
def insertKeyValuePair(self, key, value):
if key not in self.cache:
if self.currentSize == self.maxSize:
self.evictLeastRecent()
else:
self.currentSize += 1
self.cache[key] = DoublyLinkedListNode(key, value)
else:
self.replaceKey(key, value)
self.updateMostRecent(self.cache[key])
# O(1) time | O(1) space
def getValueFromKey(self, key):
if key not in self.cache:
return None
self.updateMostRecent(self.cache[key])
return self.cache[key].value
# O(1) time | O(1) space
def getMostRecentKey(self):
return self.listOfMostRecent.head.key
def evictLeastRecent(self):
keyToRemove = self.listOfMostRecent.tail.key
self.listOfMostRecent.removeTail()
del self.cache[keyToRemove]
def updateMostRecent(self, node):
self.listOfMostRecent.setToHead(node)
def replaceKey(self, key, value):
if key not in self.cache:
raise Exception("The provided key isn't in the cache!")
self.cache[key].value = value
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def setToHead(self, node):
if self.head == node:
return
elif self.head is None:
self.head = node
self.tail = node
elif self.head == self.tail:
self.tail.prev = node
self.head = node
self.head.next = self.tail
else:
if self.tail == node:
self.removeTail()
node.removeBindings()
self.head.prev = node
node.next = self.head
self.head = node
def removeTail(self):
if self.tail is None:
return
if self.tail == self.head:
self.head = None
self.tail = None
return
self.tail = self.tail.prev
self.tail.next = None
class DoublyLinkedListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
def removeBindings(self):
if self.prev is not None:
self.prev.next = self.next
if self.next is not None:
self.next.prev = self.prev
self.prev = None
self.next = None