---
description: Implement the LRUCache class
---

# LRU Cache

![](https://2282290372-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MJcwT61yCiz5H4ZddkF%2F-MfxHnGKqS_cb_M1X52s%2F-MfxPnVxK4CBtGNfYotF%2Fimage.png?alt=media\&token=afa3e861-1c1a-4e77-8d38-a51955647e86)

![](https://2282290372-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MJcwT61yCiz5H4ZddkF%2F-MfxHnGKqS_cb_M1X52s%2F-MfxPwqh_0QaTYtYiTJp%2Fimage.png?alt=media\&token=a028fe00-477f-44fb-a4a2-e9b27012281d)

```python
class ListNode:
    def __init__(self,key=-1, value=-1, next=None, prev=None):
        self.key = key
        self.value = value
        self.next = next
        self.prev = prev

class LRUCache:
     def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = dict()
        self.head = ListNode()
        self.tail = ListNode()
        self.head.next = self.tail
        self.tail.prev = self.head

     def get(self, key: int) -> int:
        if key not in self.cache: return -1
        
        node = self.cache[key]
        v = node.value
        self.remove(node)
        self.add(node)
        return v

     def put(self, key: int, value: int) -> None:
        if key not in self.cache:
            if len(self.cache) >= self.capacity:
                self.pop_lru()
            self.add(ListNode(key,value))
        else:
            node = self.cache[key]
            node.value = value
            self.remove(node)
            self.add(node)
    
    def add(self, node:ListNode) -> None:
        self.tail.prev.next = node
        node.prev = self.tail.prev
        node.next = self.tail
        self.tail.prev = node
        self.cache[node.key] = node
    
    def remove(self, node: ListNode) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev
        del self.cache[node.key]
    
    def pop_lru(self) -> None:
        self.remove(self.head.next)
```

### Approach2: Inneficient using Queue properties

```python
from collections import deque, namedtuple
class LRUCache:

    def __init__(self, capacity: int):
        self.deq = deque()
        self.size = capacity
        self.Pair = namedtuple('pair', ['key', 'value'])
        
    def get(self, key: int) -> int:
        index = self.find(key)
        if index == -1: return -1
        value = self.deq[index].value
        del self.deq[index]
        self.deq.append(self.Pair(key=key, value=value))
        return value
    
    def put(self, key: int, value: int) -> None:
        index = self.find(key)
        
        if index == -1:
            if len(self.deq) >= self.size:
                del self.deq[0]
        else:
            del self.deq[index]
        self.deq.append(self.Pair(key=key, value=value))
        
    def find(self, key: int) -> int:
        for index, pair in enumerate(self.deq):
            if pair.key == key:
                return index
        return -1
```
