
Problem
Solution
Submissions
LRU Cache
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Design and implement a data structure for a Least Recently Used (LRU) cache. The cache should support the following operations: Get and Put.
Get(key): Get the value of the key if the key exists in the cache, otherwise return -1.Put(key, value): Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item.
Both operations should have O(1) time complexity.
Example 1
- 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]
- Explanation:
- LRUCache lruCache = new LRUCache(2); // capacity = 2
- lruCache.Put(1, 1);
- lruCache.Put(2, 2);
- lruCache.Get(1); // returns 1
- lruCache.Put(3, 3); // evicts key 2
- lruCache.Get(2); // returns -1 (not found)
- lruCache.Put(4, 4); // evicts key 1
- lruCache.Get(1); // returns -1 (not found)
- lruCache.Get(3); // returns 3
- lruCache.Get(4); // returns 4
Example 2
- Input: ["LRUCache", "put", "get", "put", "get", "get"] [[1], [2, 1], [2], [3, 2], [2], [3]]
- Output: [null, null, 1, null, -1, 2]
- Explanation:
- LRUCache lruCache = new LRUCache(1); // capacity = 1
- lruCache.Put(2, 1);
- lruCache.Get(2); // returns 1
- lruCache.Put(3, 2); // evicts key 2
- lruCache.Get(2); // returns -1 (not found)
- lruCache.Get(3); // returns 2
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 a hash map and a doubly linked list
- The hash map provides O(1) lookup by key
- The doubly linked list helps maintain the order of usage
- When an item is accessed, move it to the front of the list
- When inserting a new item at capacity, remove the last item from the list