BackendML

LRU Cache

Medium3 min read
The LRU Cache problem asks us to design a cache that supports fast get and put operations while automatically removing the least recently used item when the cache reaches its capacity.

Problem

Design a data structure that supports two operations: get and put.

The get(key) operation should return the value associated with the key if it exists in the cache. Accessing a key makes it the most recently used item.

The put(key, value) operation should insert or update the value associated with the key. The inserted or updated key becomes the most recently used item.

When the cache reaches its capacity and a new item needs to be inserted, the least recently used item must be removed. Both get and put should run in O(1) average time.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

LRUCache cache = new LRUCache(2);

cache.put(1, 1);
cache.put(2, 2);

cache.get(1);

cache.put(3, 3);

cache.get(2);

cache.put(4, 4);

cache.get(1);
cache.get(3);
cache.get(4);

Output

1
-1
-1
3
4

Solution

This solution combines a HashMap and a Doubly Linked List to achieve O(1) average time for both get and put.

The HashMap provides constant-time access to a cache entry using its key. The Doubly Linked List maintains the order of usage, with the most recently used item near the head and the least recently used item near the tail.

Whenever an item is accessed using get, it is moved to the front of the linked list because it has become the most recently used item.

When a new item is inserted using put, it is also placed at the front. If the key already exists, its value is updated and the existing node is moved to the front.

If the cache exceeds its capacity, the node at the end of the linked list is removed because it represents the least recently used item. The corresponding entry is also removed from the HashMap.

The doubly linked list is important because removing or moving a node requires updating both its previous and next pointers. With direct references to these nodes, these operations can be performed in O(1) time.
class LRUCache {

    private class Node {
        int key;
        int value;
        Node prev;
        Node next;

        Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private final int capacity;
    private final Map<Integer, Node> cache;

    private final Node head;
    private final Node tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new HashMap<>();

        head = new Node(0, 0);
        tail = new Node(0, 0);

        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        if (!cache.containsKey(key)) {
            return -1;
        }

        Node node = cache.get(key);

        remove(node);
        insertAtFront(node);

        return node.value;
    }

    public void put(int key, int value) {

        if (cache.containsKey(key)) {
            Node node = cache.get(key);

            node.value = value;

            remove(node);
            insertAtFront(node);

            return;
        }

        Node node = new Node(key, value);

        cache.put(key, node);
        insertAtFront(node);

        if (cache.size() > capacity) {
            Node lru = tail.prev;

            remove(lru);
            cache.remove(lru.key);
        }
    }

    private void remove(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void insertAtFront(Node node) {
        node.next = head.next;
        node.prev = head;

        head.next.prev = node;
        head.next = node;
    }
}

Complexity

The get operation performs a HashMap lookup and moves the corresponding node in the doubly linked list. Both operations take O(1) average time.

The put operation also performs constant-time HashMap operations and constant-time linked-list insertion or removal, resulting in O(1) average time.

The HashMap and doubly linked list store at most capacity entries, so the space complexity is O(capacity).

Comments

No comments yet. Ask a question or share what helped.