forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LRU_Cache.py
88 lines (74 loc) · 2.38 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
class LRUCache:
def __init__(self, maxSize):
self.maxSize = maxSize or 1
self.cache = {}
self.currentSize = 0
self.listOfMostRecent = DoublyLinkedList()
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])
def getValueFromKey(self, key):
if key not in self.cache:
return None
self.updateMostRecent(self.cache[key])
return self.cache[key].value
def getMostRecentKey(self):
return self.listOfMostRecent.head.key
def evictLeastRecent(self):
keyToRemove = self.listOfMostRecent.tail.key
self.listOfMostRecent.removeTail()
del self.cache[keyToRemove]
def replaceKey(self, key, value):
self.cache[key].value = value
def updateMostRecent(self, listNode):
self.listOfMostRecent.setHeadTo(listNode)
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def setHeadTo(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.removeBinding()
self.head.prev = node
node.next = self.head
self.head = node
def removeTail(self):
if self.tail is None:
return
if self.head == self.tail:
self.head = None
self.tail = None
return
self.tail = self.tail.prev
self.tail.next = None
class DoublyLinkedListNode:
def __init__(self, key, val):
self.key = key
self.value = val
self.next = None
self.prev = None
def removeBinding(self):
if self.prev is not None:
self.prev.next = self.next
if self.next is not None:
self.next.prev = self.prev
self.next = None
self.prev = None