Skip to the solution
HardDSA15 min read

How do you design an LRU cache?

1.2k views

The problem

Question presented to candidate: "Design an LRU cache class in Python with get(key) and put(key, value), both O(1). When it is full, put must evict the least recently used key. Then tell me what you would change for a real service."

What a strong answer should cover:

  • LRU definition and the two jobs: O(1) lookup by key and O(1) maintenance of recency order.
  • The standard structure: a dict from key to node plus a doubly linked list ordered by recency, with eviction at the old end.
  • Both get and put count as a use; updating an existing key never evicts; a miss leaves the order alone.
  • The Python shortcut collections.OrderedDict with move_to_end(key) and popitem(last=False), and why a plain dict is awkward (assigning to an existing key does not move it).
  • Beyond the coding round: LRU vs FIFO/LFU, thrashing on scans, locks for threads, TTL, and functools.lru_cache for memoising functions.

Clarifying questions expected:

  • Is capacity counted in entries or bytes, and can it be 0?
  • Does put on an existing key count as a use?
  • Is the cache shared between threads?

Code / implementation expected: Yes โ€” an LRUCache class in Python 3, using OrderedDict or a hand-written dict plus doubly linked list.

  • lru
  • design

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonLRU trace: every get and put, with the eviction and the recency order
PythonHit rate on one workload: LRU vs FIFO, and the loop that defeats LRU

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 129 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How does the KMP string-matching algorithm work?

Continue