Coding Interview Questions

LRU Cache: HashMap + Doubly Linked List

Implement LRU cache with O(1) get and put.

Why Interviewers Ask This

The single most-asked system-structure coding problem. LeetCode 146, asked at every FAANG.

How to Answer

  1. 1

    Requirement: get(key) and put(key,val) both O(1); when capacity exceeded, evict least-recently-used.

  2. 2

    HashMap alone: O(1) lookup but no order. Linked list alone: ordered but O(n) lookup. Combine: hashmap → list-node, doubly linked list for O(1) unlink.

  3. 3

    On get(key): map.get(key) → unlink node → move to head. On put(key): if exists update+move, else new node at head, if size > capacity remove tail.

  4. 4

    Doubly linked list is needed so we can unlink a middle node in O(1) (we know both neighbors).

  5. 5

    Use sentinel head/tail dummies to avoid null checks on edges.

Sample Answer

HashMap points to doubly-linked-list nodes. get: look up node in map, unlink, reinsert at head, return value. put: if present, update and move to head; if not, create node, insert at head, if size over cap, remove tail and delete from map. Every op is O(1) because: map is O(1), unlinking a known node in a doubly-linked list is O(1), head/tail insertion is O(1). Java has LinkedHashMap which is literally this data structure — override removeEldestEntry and you're done in 5 lines — but the interview wants you to demonstrate the internals. The two gotchas: always update the map when you delete the tail node, and use sentinel head/tail dummies so you never null-check.

Pro Tips

  • LinkedHashMap(accessOrder=true) is the 5-line Java version for real code.

  • LFU (frequency-based) is a common follow-up — harder because you need a frequency bucket structure.

  • HireMe AI (即答侠) has the 40-line Java version memorized, plus the LFU extension.

Frequently Asked Questions

Why not a singly linked list?

To unlink a middle node in O(1) you need to know its predecessor. In a singly linked list you'd have to walk from head.

What happens under concurrent access?

Naive impl isn't thread-safe. For concurrent LRU, consider Caffeine or wrap with a lock — full lock-free LRU is hard.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free