Library

Volume 3 · Coding Problems & Data Structures

Notebook
Sign in

Section 18

LRU Cache Implementation (Full Working Code)

878 words · about 4 min

Concept: Evicts the least-recently-used item when capacity is exceeded. Requires O(1) get and put, achieved via HashMap + Doubly Linked List: the hash map gives O(1) lookup, the linked list gives O(1) reordering/eviction without shifting elements.

Python Implementation

class Node:
    """Doubly linked list node for LRU Cache."""
    __slots__ = ['key', 'value', 'prev', 'next']

    def __init__(self, key: int = 0, value: int = 0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None


class LRUCache:
    """
    Least Recently Used (LRU) Cache with O(1) get and put.

    Head (right after dummy head) = most recently used.
    Tail (right before dummy tail) = least recently used.

    Thread-safety note: NOT thread-safe. Wrap with threading.Lock()
    for concurrent access in production.
    """

    def __init__(self, capacity: int):
        if capacity <= 0:
            raise ValueError("Capacity must be positive")
        self.capacity = capacity
        self.cache: dict[int, Node] = {}

        self.head = Node()  # sentinel: most recently used end
        self.tail = Node()  # sentinel: least recently used end
        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._move_to_head(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            node.value = value
            self._move_to_head(node)
        else:
            node = Node(key, value)
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.capacity:
                removed = self._remove_tail()
                del self.cache[removed.key]

    def _add_to_head(self, node: Node) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _remove_node(self, node: Node) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def _move_to_head(self, node: Node) -> None:
        self._remove_node(node)
        self._add_to_head(node)

    def _remove_tail(self) -> Node:
        node = self.tail.prev
        self._remove_node(node)
        return node


# --- Usage ---
cache = LRUCache(3)
cache.put(1, 10)
cache.put(2, 20)
cache.put(3, 30)
cache.get(1)          # 10, moves 1 to front
cache.put(4, 40)      # evicts 2 (LRU)
assert cache.get(2) == -1

C# Implementation

using System;
using System.Collections.Generic;

public class LRUCache
{
    private class Node
    {
        public int Key;
        public int Value;
        public Node? Prev;
        public Node? Next;
    }

    private readonly int _capacity;
    private readonly Dictionary<int, Node> _cache;
    private readonly Node _head;   // sentinel: most recently used end
    private readonly Node _tail;   // sentinel: least recently used end
    private readonly object _lock = new();   // for the thread-safe variant

    public LRUCache(int capacity)
    {
        if (capacity <= 0) throw new ArgumentException("Capacity must be positive");
        _capacity = capacity;
        _cache = new Dictionary<int, Node>(capacity);
        _head = new Node();
        _tail = new Node();
        _head.Next = _tail;
        _tail.Prev = _head;
    }

    public int Get(int key)
    {
        lock (_lock)
        {
            if (!_cache.TryGetValue(key, out var node)) return -1;
            MoveToHead(node);
            return node.Value;
        }
    }

    public void Put(int key, int value)
    {
        lock (_lock)
        {
            if (_cache.TryGetValue(key, out var existing))
            {
                existing.Value = value;
                MoveToHead(existing);
                return;
            }

            var node = new Node { Key = key, Value = value };
            _cache[key] = node;
            AddToHead(node);

            if (_cache.Count > _capacity)
            {
                var removed = RemoveTail();
                _cache.Remove(removed.Key);
            }
        }
    }

    private void AddToHead(Node node)
    {
        node.Prev = _head;
        node.Next = _head.Next;
        _head.Next!.Prev = node;
        _head.Next = node;
    }

    private void RemoveNode(Node node)
    {
        node.Prev!.Next = node.Next;
        node.Next!.Prev = node.Prev;
    }

    private void MoveToHead(Node node)
    {
        RemoveNode(node);
        AddToHead(node);
    }

    private Node RemoveTail()
    {
        var node = _tail.Prev!;
        RemoveNode(node);
        return node;
    }
}

// --- Usage ---
var cache = new LRUCache(3);
cache.Put(1, 10);
cache.Put(2, 20);
cache.Put(3, 30);
Console.WriteLine(cache.Get(1));  // 10
cache.Put(4, 40);                 // evicts 2
Console.WriteLine(cache.Get(2));  // -1

Complexity & Interview Follow-ups

Operation Time Space
Get / Put O(1) —
Overall — O(capacity)
  • Thread safety: wrap with lock/threading.Lock(), or use ConcurrentDictionary + a separate synchronized linked list, or shard the cache by key hash across N locks to reduce contention.
  • TTL support: store an expiry timestamp on each node; check on get, lazily evict on access, and optionally run a background sweeper.
  • Why not just use OrderedDict (Python) or LinkedList<T> (C#) directly? You can — OrderedDict.move_to_end() + popitem(last=False) implements LRU in ~10 lines — but interviewers want to see you understand the underlying mechanics before reaching for the shortcut. In production code, prefer the built-in / IMemoryCache with a size limit, or functools.lru_cache for pure functions.