146. LRU Cache

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity.

class Node:
    def __init__(self, val, key):
        self.val = val
        self.key = key
        self.prev = None
        self.nxt = None
        
class DBList:
    def __init__(self):
        self.dummy = Node(None, None)
        self.dummy.nxt = self.dummy
        self.dummy.prev = self.dummy
        self.size = 0
        
    def remove(self, node):
        node.prev.nxt = node.nxt
        node.nxt.prev = node.prev
        self.size -= 1
        
    def append(self, node):
        node.prev = self.dummy.prev
        node.nxt = self.dummy
        self.dummy.prev.nxt = node
        self.dummy.prev = node
        self.size += 1
        
class LRUCache:

    def __init__(self, capacity: int):
        self.data = {}
        self.dblist = DBList()
        self.cap = capacity
        
    def get(self, key: int) -> int:
        if key not in self.data:
            return -1
        
        val = self.data[key].val
        self.dblist.remove(self.data[key])
        self.dblist.append(self.data[key])
        return val
        
    def put(self, key: int, value: int) -> None:

        if key in self.data:
            self.dblist.remove(self.data[key])
            self.data[key].val = value
            self.dblist.append(self.data[key])
            return
        
        if self.dblist.size == self.cap:
            del self.data[self.dblist.dummy.nxt.key]
            self.dblist.remove(self.dblist.dummy.nxt)
            
        self.data[key] = Node(value, key)
        self.dblist.append(self.data[key])

Related question: 460. LFU Cache