Low-level design: an LRU cache

Design and code a Least Recently Used cache with O(1) get and put: the hash map plus doubly linked list, clean class design in four languages, and the follow-ups interviewers ask: thread safety, TTLs and LFU.

intermediate9 min readBy CureBugs EditorialUpdated 5 Nov 2026

"Design an LRU cache" is the most-asked low-level design question in Indian product-company interviews, and it shows up in DSA rounds too. It is small enough to code in 30 minutes, but it tests three things at once: whether you can pick the right data structures, whether you can turn them into clean classes, and whether you can reason about what happens when real systems use your code: concurrently, with expiring entries, under memory pressure.

This article walks through the design the way you'd present it in an interview: requirements, the key insight, the classes, code in four languages, and the follow-ups.

Requirements

Clarify before you code. A typical version:

  1. get(key) returns the value if present, otherwise -1 (or "not found"). A successful get marks the key as most recently used.
  2. put(key, value) inserts or updates the key and marks it most recently used.
  3. The cache has a fixed capacity. When an insert would exceed it, evict the least recently used key.
  4. Both operations run in O(1) average time.

Good questions to ask: Can capacity be zero? Are keys and values integers or generic? Does put on an existing key count as a use? (Yes, almost always.) Is it used from multiple threads? (Often a follow-up, so mention it now and park it.)

The key insight: two structures, one job each

No single standard structure does both jobs in O(1):

  • A hash map finds a key in O(1), but has no notion of order.
  • A list ordered by recency knows who to evict, but finding a key in it is O(n).

The classic solution combines them. Keep a doubly linked list ordered from most to least recently used, and a hash map from key to list node. Then:

  • get: look up the node in the map (O(1)), unlink it and move it to the front (O(1) because the list is doubly linked and the node knows its neighbours).
  • put: if the key exists, update and move to front. Otherwise create a node at the front; if over capacity, remove the node at the back (O(1)) and delete its key from the map, which is why each node stores its key.

Two sentinel nodes (a dummy head and a dummy tail that are never removed) eliminate every "is the list empty?" and "is this the first node?" special case. Interviewers notice this; it is the difference between 40 lines of edge cases and 10 clean ones.

The node right after the head is the most recently used; the node right before the tail is the next to be evicted.

Class design

Keep the responsibilities separate, because interviewers grade the design as much as the algorithm:

  • Node: key, value, prev, next. A plain data holder.
  • The list operations: addToFront(node), remove(node), removeLast(). Small private helpers (or a separate DoublyLinkedList class if you want to show OOP explicitly).
  • LRUCache: owns the map and the list, exposes only get and put. Nothing outside it can see a node.

The implementation

class Node:
    __slots__ = ("key", "value", "prev", "next")

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


class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.map = {}                      # key -> node
        self.head, self.tail = Node(), Node()  # sentinels
        self.head.next, self.tail.prev = self.tail, self.head

    def get(self, key: int) -> int:
        node = self.map.get(key)
        if node is None:
            return -1
        self._move_to_front(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        if self.capacity <= 0:
            return
        node = self.map.get(key)
        if node is not None:
            node.value = value
            self._move_to_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev           # least recently used
            self._remove(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._add_to_front(node)

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

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

    def _move_to_front(self, node: Node) -> None:
        self._remove(node)
        self._add_to_front(node)

Walk through an example

Capacity 2:

OperationList (most → least recent)Returns
put(1, 10)1
put(2, 20)2, 1
get(1)1, 210
put(3, 30)3, 1 (evicts 2)
get(2)3, 1-1
put(1, 11)1, 3 (the update moves 1 to the front)
get(3)3, 130

Say this table out loud in the interview, or trace it on the code. It catches the two most common bugs: forgetting that get changes recency, and forgetting to remove the evicted key from the map.

Complexity

  • get and put: O(1) average: one hash lookup plus a constant number of pointer changes.
  • Space: O(capacity): one map entry and one node per key.

Shortcuts, and when not to use them

Most languages have an ordered map that does the list work for you:

  • Java: LinkedHashMap with accessOrder = true, overriding removeEldestEntry.
  • Python: collections.OrderedDict with move_to_end and popitem(last=False).
  • JavaScript: a Map iterates in insertion order, so deleting and re-inserting a key moves it to the end, and map.keys().next().value is the oldest key.

Mention these, because it shows you know your language. But in a low-level design round, the interviewer almost always wants the hand-built version, because the point is to see you design the structure. Ask: "Shall I use LinkedHashMap, or would you like me to build the list?"

Follow-ups interviewers ask

Make it thread-safe

The simplest correct answer is one lock around get and put. Note that even get writes (it moves a node), so a read-write lock doesn't help: every operation needs exclusive access.

One lock becomes a bottleneck under heavy concurrency. The standard fix is sharding: split the cache into N independent LRU caches (each with its own lock), and route each key by hash(key) % N. Eviction becomes "least recently used within the shard", which is approximate but almost always acceptable. This is how libraries like Guava and Caffeine (Java) and many Go caches scale.

Add a time-to-live (TTL)

Store an expiresAt on each node. On get, treat an expired node as missing (remove it and return -1). That is lazy expiry: cheap, but expired entries still occupy space until someone touches them or they reach the tail. For tighter memory, add a background sweep, or keep a second structure (a min-heap or timing wheel ordered by expiry) to evict expired entries proactively. Redis combines lazy expiry with periodic random sampling.

Evict by frequency instead (LFU)

Least Frequently Used evicts the key with the fewest accesses, breaking ties by recency. The O(1) design keeps a map from key to node, a map from frequency to a doubly linked list of nodes with that frequency, and the current minimum frequency. It is a common "harder version". Know the shape even if you don't code it.

Size by bytes, not entries

Real caches limit memory, not key counts. Track each entry's size and evict from the tail until the total fits. Large values can force several evictions for one insert.

How it's used in real systems

LRU is everywhere: database buffer pools, CPU caches (approximately), CDN edge caches, and application caches in front of slow services. It works well when recent use predicts future use, and badly for scans that touch every item once, which flush everything useful. That is why databases often use variants like LRU-K or a "midpoint insertion" strategy. Our caching strategies article covers how caches like this fit into a larger system.

Edge cases to test

  • Capacity 0 (or 1).
  • put on an existing key updates the value and recency.
  • get on a missing key.
  • Evicting the only key.
  • A long sequence of puts larger than capacity, where the map size must never exceed capacity.

Practise it in the LRU Cache problem, where hidden tests include large sequences that will catch an O(n) shortcut.

Mock interview

Can you explain it when someone pushes back?

Interviewers rarely ask for a definition. They ask why you'd pick this over that, and what breaks at ten times the load. A mock round finds those gaps before the real one does.

  • A question on your own project, then a design problem
  • The interviewer probes the parts you skim over
  • A scored report that quotes your answers and says what to fix
Start a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
Low-level design•beginnerStart here

How to learn low-level design (LLD): the complete roadmap

5 min read
Case studies•intermediate

Design a flash sale (10,000 phones, a million buyers)

16 min read
Case studies•intermediate

Design Google Docs: collaborative editing

12 min read
Low-level design: an LRU cache · CureBugs