MediumNo. 0146

LRU Cache — LeetCode 146 Python Solution

Topics
Design, Hash Table, Linked List, Doubly-Linked List
Reading time
10 min

The problem

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.

Example

Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
LRUCache lRUCache = new LRUCache(2);

Python solution

PythonSolution
class Node:
    def __init__(self, key: int = 0, val: int = 0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None


class LRUCache:

    def __init__(self, capacity: int):
        self.size = 0
        self.capacity = capacity
        self.cache = {}
        self.head = Node()
        self.tail = Node()
        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]
        self.remove_node(node)
        self.add_to_head(node)
        return node.val

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            self.remove_node(node)
            node.val = value
            self.add_to_head(node)
        else:
            node = Node(key, value)
            self.cache[key] = node
            self.add_to_head(node)
            self.size += 1
            if self.size > self.capacity:
                node = self.tail.prev
                self.cache.pop(node.key)
                self.remove_node(node)
                self.size -= 1

    def remove_node(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def add_to_head(self, node):
        node.next = self.head.next
        node.prev = self.head
        self.head.next = node
        node.next.prev = node


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

Complexity

Time
O(1)
Space · auxiliary
O(capacity)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 146. LRU Cache is filed here because LeetCode tags it Linked List and Doubly-Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0432All O`one Data StructureHard
0460LFU CacheHard
1797Design Authentication ManagerMedium
0355Design TwitterMedium
0705Design HashSetEasy
0706Design HashMapEasy

Frequently asked questions

How hard is LeetCode 146. LRU Cache?

LeetCode 146. LRU Cache is rated Medium on LeetCode.

What is the time complexity of LeetCode 146. LRU Cache?

The Python solution on this page runs in O(1).

What is the space complexity of LeetCode 146. LRU Cache?

The Python solution on this page uses O(capacity) auxiliary space.

What topics does LeetCode 146. LRU Cache cover?

LeetCode 146. LRU Cache is tagged Design, Hash Table, Linked List and Doubly-Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.