
Problem
Solution
Submissions
LRU Cache
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Design and implement an LRU (Least Recently Used) cache in C#. The cache should support Get(key)
and Put(key, value)
operations with O(1) time complexity.
- Get(key)
: Return the value of the key if it exists in the cache, otherwise return -1.
- Put(key, value)
: Insert or update the value of the key. If the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item.
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); // Cache capacity is 2
- lRUCache.put(1, 1); // cache is {1=1}
- lRUCache.put(2, 2); // cache is {1=1, 2=2}
- lRUCache.get(1); // return 1
- lRUCache.put(3, 3); // LRU key was 2, cache is {1=1, 3=3}
- lRUCache.get(2); // returns -1 (not found)
- lRUCache.put(4, 4); // LRU key was 1, cache is {4=4, 3=3}
- lRUCache.get(1); // return -1 (not found)
- lRUCache.get(3); // return 3
- lRUCache.get(4); // return 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); // Cache capacity is 1
- lRUCache.put(2, 1); // cache is {2=1}
- lRUCache.get(2); // return 1
- lRUCache.put(3, 2); // LRU key was 2, cache is {3=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 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, while the doubly linked list helps maintain the order of usage
- Move accessed items to the front of the list to mark them as recently used
- When capacity is reached, remove the least recently used item from the back of the list
- Ensure proper handling of pointers when updating the linked list