KatInterview

146. LRU Cache

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core challenge is to design a data structure, an LRU Cache, that supports get and put operations in O(1) average time complexity. An LRU (Least Recently Used) cache evicts the item that has not been accessed for the longest time when its capacity is full.

Solution

LRU Cache in Python

class Node:
    # Node for the doubly linked list
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = {}  # Map from key to node for O(1) lookup
        
        # Dummy head and tail for the doubly linked list
        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):
        # Helper to remove a node from the list
        prev_node = node.prev
        next_node = node.next
        prev_node.next = next_node
        next_node.prev = prev_node
        
    def _add_to_head(self, node: Node):
        # Helper to add a node right after the head (most recently used)
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def get(self, key: int) -> int:
        if key in self.cache:
            node = self.cache[key]
            # Move the accessed node to the head
            self._remove(node)
            self._add_to_head(node)
            return node.val
        return -1

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            # Key exists, update value and move to head
            node = self.cache[key]
            node.val = value
            self._remove(node)
            self._add_to_head(node)
        else:
            # Key does not exist, add a new node
            if len(self.cache) == self.capacity:
                # Evict the least recently used node (at the tail)
                lru = self.tail.prev
                self._remove(lru)
                del self.cache[lru.key]
            
            new_node = Node(key, value)
            self.cache[key] = new_node
            self._add_to_head(new_node)


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

LRU Cache in Java

class LRUCache {
    // Inner class for the doubly linked list node
    private class Node {
        int key;
        int value;
        Node prev;
        Node next;
    }

    private final int capacity;
    // Hash map for O(1) lookup of key -> node
    private Map<Integer, Node> cache;
    // Dummy head and tail for the doubly linked list
    private Node head, tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new HashMap<>();
        
        // Initialize dummy head and tail nodes
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.prev = head;
    }

    // Helper to add a node right after the head (most recently used)
    private void addNode(Node node) {
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }

    // Helper to remove a node from its current position
    private void removeNode(Node node) {
        Node prev = node.prev;
        Node next = node.next;
        prev.next = next;
        next.prev = prev;
    }

    // Helper to move a node to the front
    private void moveToHead(Node node) {
        removeNode(node);
        addNode(node);
    }

    // Helper to pop the node at the tail (least recently used)
    private Node popTail() {
        Node res = tail.prev;
        removeNode(res);
        return res;
    }

    public int get(int key) {
        Node node = cache.get(key);
        // If key doesn't exist, return -1
        if (node == null) {
            return -1;
        }
        // Key exists, move it to the head (most recently used)
        moveToHead(node);
        return node.value;
    }
    
    public void put(int key, int value) {
        Node node = cache.get(key);

        if (node != null) {
            // Key exists, update the value and move it to the head
            node.value = value;
            moveToHead(node);
        } else {
            // Key doesn't exist, create a new node
            Node newNode = new Node();
            newNode.key = key;
            newNode.value = value;

            // Add it to the cache and the list
            cache.put(key, newNode);
            addNode(newNode);

            // If capacity is exceeded, evict the least recently used item
            if (cache.size() > capacity) {
                Node tailNode = popTail();
                cache.remove(tailNode.key);
            }
        }
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

LRU Cache in C++

class LRUCache {
private:
    // Node for the doubly linked list
    struct DLinkedNode {
        int key;
        int value;
        DLinkedNode* prev;
        DLinkedNode* next;
        DLinkedNode(): key(0), value(0), prev(nullptr), next(nullptr) {}
        DLinkedNode(int _key, int _value): key(_key), value(_value), prev(nullptr), next(nullptr) {}
    };

    // Hash map to store key -> node pointer for O(1) lookup
    std::unordered_map<int, DLinkedNode*> cache;
    // Dummy head and tail for the doubly linked list
    DLinkedNode* head;
    DLinkedNode* tail;
    int capacity;

    // Helper function to add a node right after the head (most recently used)
    void addToHead(DLinkedNode* node) {
        node->prev = head;
        node->next = head->next;
        head->next->prev = node;
        head->next = node;
    }

    // Helper function to remove a node from the list
    void removeNode(DLinkedNode* node) {
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }

    // Helper function to move a node to the head
    void moveToHead(DLinkedNode* node) {
        removeNode(node);
        addToHead(node);
    }
    
    // Helper function to remove the tail node (least recently used)
    DLinkedNode* removeTail() {
        DLinkedNode* lruNode = tail->prev;
        removeNode(lruNode);
        return lruNode;
    }

public:
    LRUCache(int capacity) : capacity(capacity) {
        // Initialize dummy head and tail nodes
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head->next = tail;
        tail->prev = head;
    }
    
    // Destructor to free allocated memory
    ~LRUCache() {
        DLinkedNode* current = head;
        while (current != nullptr) {
            DLinkedNode* next = current->next;
            delete current;
            current = next;
        }
    }

    int get(int key) {
        // If key is not in the cache, return -1
        if (cache.find(key) == cache.end()) {
            return -1;
        }
        // Key exists, get the node
        DLinkedNode* node = cache[key];
        // Move the accessed node to the head to mark it as most recently used
        moveToHead(node);
        return node->value;
    }
    
    void put(int key, int value) {
        // If key already exists
        if (cache.find(key) != cache.end()) {
            DLinkedNode* node = cache[key];
            // Update its value
            node->value = value;
            // Move it to the head
            moveToHead(node);
        } else {
            // Key does not exist, create a new node
            DLinkedNode* newNode = new DLinkedNode(key, value);
            // Add it to the hash map and the list head
            cache[key] = newNode;
            addToHead(newNode);
            
            // If capacity is exceeded, evict the least recently used element
            if (cache.size() > capacity) {
                DLinkedNode* lru = removeTail();
                // Remove the LRU from the hash map
                cache.erase(lru->key);
                // Free the memory of the evicted node
                delete lru;
            }
        }
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

LRU Cache in TypeScript

class DLinkedNode {
    key: number;
    value: number;
    prev: DLinkedNode | null;
    next: DLinkedNode | null;

    constructor(key: number = 0, value: number = 0) {
        this.key = key;
        this.value = value;
        this.prev = null;
        this.next = null;
    }
}

class LRUCache {
    private capacity: number;
    // Map for O(1) lookup of key -> node
    private cache: Map<number, DLinkedNode>;
    // Dummy head and tail for the doubly linked list
    private head: DLinkedNode;
    private tail: DLinkedNode;

    constructor(capacity: number) {
        this.capacity = capacity;
        this.cache = new Map<number, DLinkedNode>();
        
        // Initialize dummy head and tail nodes
        this.head = new DLinkedNode();
        this.tail = new DLinkedNode();
        this.head.next = this.tail;
        this.tail.prev = this.head;
    }

    // Helper to remove a node from its current position
    private _removeNode(node: DLinkedNode): void {
        const prev = node.prev!;
        const next = node.next!;
        prev.next = next;
        next.prev = prev;
    }

    // Helper to add a node right after the head (most recently used)
    private _addNodeToHead(node: DLinkedNode): void {
        node.prev = this.head;
        node.next = this.head.next;
        this.head.next!.prev = node;
        this.head.next = node;
    }
    
    // Helper to move a node to the head
    private _moveToHead(node: DLinkedNode): void {
        this._removeNode(node);
        this._addNodeToHead(node);
    }

    get(key: number): number {
        const node = this.cache.get(key);
        // If key doesn't exist, return -1
        if (!node) {
            return -1;
        }
        // Key exists, move it to the head
        this._moveToHead(node);
        return node.value;
    }

    put(key: number, value: number): void {
        const node = this.cache.get(key);
        if (node) {
            // Key exists, update its value and move to head
            node.value = value;
            this._moveToHead(node);
        } else {
            // Key does not exist, create a new node
            const newNode = new DLinkedNode(key, value);
            this.cache.set(key, newNode);
            this._addNodeToHead(newNode);

            // If capacity is exceeded, evict the least recently used node
            if (this.cache.size > this.capacity) {
                const lru = this.tail.prev!;
                this._removeNode(lru);
                this.cache.delete(lru.key);
            }
        }
    }
}

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

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.