Design and implement a Least Recently Used (LRU) Cache data structure that efficiently manages a limited amount of storage space by automatically evicting the least recently accessed items when capacity is exceeded.

Your LRUCache class should support:

  • LRUCache(int capacity): Initialize the cache with a positive capacity
  • int get(int key): Return the value associated with the key if it exists, otherwise return -1. This operation marks the key as recently used.
  • void put(int key, int value): Insert or update the key-value pair. If adding this pair exceeds capacity, remove the least recently used key first. This operation marks the key as recently used.

Challenge: Both get and put operations must run in O(1) average time complexity.

Example:

LRUCache cache = new LRUCache(2);
cache.put(1, 1);  // cache: {1=1}
cache.put(2, 2);  // cache: {1=1, 2=2}
cache.get(1);     // returns 1, cache: {2=2, 1=1}
cache.put(3, 3);  // evicts key 2, cache: {1=1, 3=3}
cache.get(2);     // returns -1 (not found)

Input & Output

example_1.py โ€” Basic Operations
$ Input: ["LRUCache","put","put","get","put","get","put","get","get","get"] [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
โ€บ Output: [null,null,null,1,null,-1,null,-1,3,4]
๐Ÿ’ก Note: LRUCache cache = new LRUCache(2); cache.put(1, 1); cache.put(2, 2); cache.get(1) returns 1; cache.put(3, 3) evicts key 2; cache.get(2) returns -1 (not found); cache.put(4, 4) evicts key 1; cache.get(1) returns -1, cache.get(3) returns 3, cache.get(4) returns 4
example_2.py โ€” Single Capacity
$ Input: ["LRUCache","put","get","put","get","get"] [[1],[2,1],[2],[3,2],[2],[3]]
โ€บ Output: [null,null,1,null,-1,2]
๐Ÿ’ก Note: With capacity 1: put(2,1), get(2) returns 1, put(3,2) evicts key 2, get(2) returns -1, get(3) returns 2
example_3.py โ€” Update Existing Key
$ Input: ["LRUCache","put","put","put","put","get","get"] [[2],[1,1],[2,2],[1,10],[2,20],[1],[2]]
โ€บ Output: [null,null,null,null,null,10,20]
๐Ÿ’ก Note: Updating existing keys should not trigger eviction, just update values and move to most recent position

Visualization

Tap to expand
LRU Cache Visual FlowStep 1:InitializeStep 2:Add ItemsStep 3:Access ItemStep 4:Evict LRUHash Mapkey1key2key3Doubly Linked List (Head โ†’ Tail = Most โ†’ Least Recent)HEAD(dummy)key3:val3key1:val1key2:val2TAIL(dummy)Most RecentLeast Recent๐ŸŽฏ Key Operations:โ€ข GET: Hash lookup O(1) + Move to head O(1) = O(1) totalโ€ข PUT: Hash lookup O(1) + List insertion/deletion O(1) = O(1) totalโ€ข EVICT: Remove tail O(1) + Hash deletion O(1) = O(1) total
Understanding the Visualization
1
Initialize Cache
Set up empty hash map and linked list with dummy head/tail nodes
2
First Access
Add new entries at the head (most recent position)
3
Subsequent Access
Move accessed items to head, maintaining recency order
4
Capacity Exceeded
Remove tail node (least recently used) and add new item at head
Key Takeaway
๐ŸŽฏ Key Insight: The combination of hash map (O(1) lookup) and doubly-linked list (O(1) insertion/deletion with known node) creates the perfect data structure for LRU cache requirements.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1)

Hash map provides O(1) lookup, doubly-linked list provides O(1) insertion/deletion with known node reference

n
2n
โœ“ Linear Growth
Space Complexity
O(capacity)

Hash map stores at most capacity entries, doubly-linked list stores at most capacity nodes

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค capacity โ‰ค 3000
  • 0 โ‰ค key โ‰ค 104
  • 0 โ‰ค value โ‰ค 105
  • At most 2 ร— 104 calls will be made to get and put
  • Both operations must run in O(1) average time complexity
Asked in
Google 75 Amazon 68 Meta 52 Microsoft 41
125.5K Views
Very High Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen