Live Coding · 21 min · free with an account

Design an LRU Cache

Lesson preview · about 30%

Combine lookup speed with recency updates.

Core idea

Explain why a hash map alone cannot evict the least recent key in O(1).

Start with the idea

Explain why a hash map alone cannot evict the least recent key in O(1). The usual design pairs lookup with an order structure and makes capacity, ownership, and mutation costs explicit.

An LRU cache evicts the least recently used entry when capacity is full. A hash map gives fast lookup by key but does not by itself maintain recency order. A doubly linked list or another order structure can move an accessed node to the most-recent end in O(1), while the map locates the node in expected O(1). The design becomes tricky at the boundary between the map and the list: both must refer to the same entry without leaving stale links or violating Rust's ownership rules.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep