#146
LRU Cache
medium· Linked Listruns: 0Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement LRUCache with a positive integer capacity, supporting get(key) returning the value (or -1 if absent) and put(key, value) inserting or updating, evicting the least recently used key when the capacity is exceeded. Both operations must run in O(1) average time.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 1242
class Node:
def __init__(self, key: int, val: int):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {}
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node: Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
def _insert(self, node: Node) -> None:
prev = self.tail.prev
prev.next = node
node.prev = prev
node.next = self.tail
self.tail.prev = node
def get(self, key: int) -> int:
if key not in self.cache:
return -1
node = self.cache[key]
self._remove(node)
self._insert(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.cache:
self._remove(self.cache[key])
node = Node(key, value)
self.cache[key] = node
self._insert(node)
if len(self.cache) > self.cap:
lru = self.head.next
self._remove(lru)
del self.cache[lru.key]
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.