Data Structures · Visualization
LRU Cache: Introduction
LRU Cache
An LRU (Least Recently Used) cache stores a limited number of items, and when it's full and a new item needs to be added, it evicts (removes) whichever item hasn't been accessed for the longest time. Time: O(1) for both get and put. Space: O(capacity).
Big-O: get / put both O(1).
LRU Cache: Introduction
LRU CacheAn LRU (Least Recently Used) cache stores a limited number of items, and when it's full and a new item needs to be added, it evicts (removes) whichever item hasn't been accessed for the longest time. It's typically built by combining a hash table (for instant lookup by key) with a doubly linked list (to track usage order, so the least recently used item is always easy to find and remove).
How LRU Cache: Introduction Works
- Set a fixed capacity for how many items the cache can hold.
- Use a hash table to map each key directly to its position in a doubly linked list.
- Keep the doubly linked list ordered by recency: most recently used at the front, least recently used at the back.
- Whenever an item is accessed or added, move it to the front; if the cache exceeds capacity, remove the item at the back.
LRU Cache: Introduction Worked Example
Input: Capacity 2. Put(1,A), Put(2,B), Get(1), Put(3,C)
- Put(1,A) → cache: [1:A] (front to back)
- Put(2,B) → cache: [2:B, 1:A]
- Get(1) → move 1 to front: cache: [1:A, 2:B]
- Put(3,C) → cache is full, evict least recently used (2) → cache: [3:C, 1:A]
Output: Final cache: {3:C, 1:A} (2 was evicted)
Press ▶ Run to watch it step by step.
from collections import OrderedDict
# Hash map for O(1) lookups + an order
# structure to decide WHAT to evict.
# example: intro key=1 value=ALRU Cache: Introduction Time & Space Complexity
When to Use LRU Cache: Introduction
- Browser caching of recently visited web pages
- Operating system page replacement (deciding which memory page to evict)
- Database query result caching
- CDN (Content Delivery Network) caching of frequently requested content
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.