
Problem
Solution
Submissions
LRU Cache Implementation
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class with get(key) and put(key, value) methods. The cache should have a fixed capacity and when the capacity is reached, it should invalidate the least recently used item before inserting a new item.
Example 1
- Input: capacity = 2, operations = ["put(1,1)", "put(2,2)", "get(1)", "put(3,3)", "get(2)", "put(4,4)", "get(1)", "get(3)", "get(4)"]
- Output: [null, null, 1, null, -1, null, -1, 3, 4]
- Explanation:
- LRUCache lru = new LRUCache(2) - Create cache with capacity 2.
- lru.put(1, 1) - Cache: {1=1}. lru.put(2, 2) - Cache: {1=1, 2=2}.
- lru.get(1) returns 1 - Cache: {2=2, 1=1} (1 becomes most recent).
- lru.put(3, 3) - Cache: {1=1, 3=3} (2 is evicted as LRU). lru.get(2) returns -1 (not found).
- lru.put(4, 4) - Cache: {3=3, 4=4} (1 is evicted as LRU).
- LRUCache lru = new LRUCache(2) - Create cache with capacity 2.
Example 2
- Input: capacity = 1, operations = ["put(2,1)", "get(2)", "put(3,2)", "get(2)", "get(3)"]
- Output: [null, 1, null, -1, 2]
- Explanation:
- LRUCache lru = new LRUCache(1) - Create cache with capacity 1.
- lru.put(2, 1) - Cache: {2=1}. lru.get(2) returns 1 - Cache: {2=1}.
- lru.put(3, 2) - Cache: {3=2} (2 is evicted as capacity is 1).
- lru.get(2) returns -1 (not found). lru.get(3) returns 2 - Cache: {3=2}.
- LRUCache lru = new LRUCache(1) - Create cache with capacity 1.
Constraints
- 1 ≤ capacity ≤ 3000
- 0 ≤ key ≤ 10^4
- 0 ≤ value ≤ 10^5
- At most 2 * 10^5 calls will be made to get and put
- Time Complexity: O(1) for both get and put operations
- Space Complexity: O(capacity)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a combination of HashMap and Doubly Linked List for O(1) operations
- HashMap stores key-node pairs for O(1) access to any node
- Doubly Linked List maintains the order of usage (most recent to least recent)
- Move accessed nodes to the front of the list to mark them as most recently used
- Remove nodes from the tail when capacity is exceeded (least recently used)