LRU Cache
mediumLeetCode Top 100NeetCode 150designhashinglinked-list
Problem
Design a cache with a fixed capacity that supports get and put in constant time. When the cache is full and a new key is added, evict the least recently used entry. Reading or updating a key marks it most recently used.
Examples
Input: capacity 2; put(1,1), put(2,2), get(1), put(3,3), get(2)
Output: get(1)=1, get(2)=-1
Adding key 3 evicts the least recently used key 2.
Constraints
- • 1 <= capacity <= 3000
- • At most 2 * 10^5 calls to get and put
Hints(tap to reveal)
- 1. A hash map gives O(1) lookup.
- 2. A doubly linked list maintains recency order for O(1) eviction.
Optimal approach(spoiler)
- Pair a hash map from key to node with a doubly linked list ordered by recency.
- On access, unlink the node and move it to the most-recent end.
- On insert past capacity, evict the node at the least-recent end.
- The map gives O(1) lookup; list splicing gives O(1) reordering.
- Both operations run in O(1) time.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor