Doubly linked lists
Each node points to the next and the previous one, so a node can be removed in O(1). An LRU cache combines one with a hash map: the most recent item sits at the front, the oldest is dropped from the back.
Practice on LeetCode: 146. LRU Cache
class Node:
def __init__(self, key=0, val=0):
self.key, self.val = key, val
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.map = {} # key -> node
self.head, self.tail = Node(), Node() # sentinels
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _add_front(self, node):
node.prev, node.next = self.head, self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key: int) -> int:
if key not in self.map:
return -1
node = self.map[key]
self._remove(node)
self._add_front(node) # now the most recent
return node.val
def put(self, key: int, value: int) -> None:
if key in self.map:
self._remove(self.map[key])
node = Node(key, value)
self.map[key] = node
self._add_front(node)
if len(self.map) > self.cap:
oldest = self.tail.prev
self._remove(oldest)
del self.map[oldest.key]
get and put in O(1): the hash map finds the node, the links move it.