Complete the code to define the main data structure used to store cache entries for fast access.
cache = [1]()The cache uses a hash map (dictionary) to store keys and their corresponding nodes for O(1) access.
Complete the code to add a new node to the front of the doubly linked list representing the most recently used item.
def add_to_front(node): node.prev = None node.next = [1] if head: head.prev = node head = node
To add a node to the front, its next pointer should point to the current head.
Fix the error in the code that removes the least recently used node from the tail of the doubly linked list.
def remove_tail(): if not tail: return prev_node = tail.prev if prev_node: prev_node.next = [1] tail = prev_node
When removing the tail, the previous node's next pointer should be set to None to mark the new end.
Fill both blanks to update the cache when a key is accessed: move the node to the front and update pointers.
def access_key(key): node = cache[key] # Remove node from current position node.prev.next = [1] node.next.prev = [2]
To remove the node, link its previous node's next to its next node, and its next node's prev to its previous node.
Fill all three blanks to implement the put operation: add new node, update cache, and remove LRU if capacity exceeded.
def put(key, value): if key in cache: node = cache[key] node.value = value access_key(key) else: new_node = Node(key, value) cache[[1]] = new_node add_to_front(new_node) if len(cache) > capacity: lru_key = tail.key remove_tail() del cache[[2]] # Optional: clear tail pointer tail = [3]
When adding a new node, store it in cache with the key. When removing LRU, delete the lru_key from cache and set tail to None if empty.