Interview conceptCoding & Algorithms

LRU Cache

Asked of: Software Engineer

Last updated

Editorial diagram of an LRU cache: a hash map points to nodes in a doubly linked list ordered from least to most recently used, with a hit moving a node to MRU.

What's being tested

This tests the LRU cache pattern: combining a hash map with a doubly linked list to support get and put in O(1) time. You must preserve both key-value lookup and recency ordering while correctly handling updates, eviction, capacity limits, and empty states.

Patterns & templates

  • Hash map + doubly linked list — map keys to nodes; list order is least-recently-used to most-recently-used.

  • Use sentinel head and tail nodes to eliminate boundary branches when removing or inserting list nodes.

  • get(key) returns -1 or the agreed absence value; on a hit, detach the node and move it to the MRU end.

  • put(key, value) updates existing nodes without increasing size; otherwise insert at MRU, then evict the LRU node if over capacity.

  • Factor helpers such as remove(node) and insert_at_front(node); each performs constant pointer updates and keeps invariants centralized.

  • Target O(1) average time for both operations and O(capacity) space; never scan the list to find keys.

  • Clarify capacity 0, repeated keys, repeated reads, missing keys, and whether values may be null or mutable objects.

Common pitfalls

Pitfall: Updating a key without moving it to MRU makes eviction order incorrect; every successful access must refresh recency.

Pitfall: Removing the LRU node from the list but not the map leaves stale entries and breaks size accounting.

Pitfall: Claiming O(1) while using an array, singly linked list, or linear search for eviction violates the required complexity.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Featured in interview prep guides

Practice questions

Related concepts