
Problem
Solution
Submissions
LRU Cache (Least Recently Used Cache)
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 10
Write a program to implement a Least Recently Used (LRU) cache. An LRU cache is a type of cache in which we remove the least recently used entry when the cache reaches its limit.
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:
- Step 1: Create cache with capacity 2
- Step 2: Put (1,1) and (2,2)
- Step 3: Get 1 returns 1
- Step 4: Put (3,3) evicts key 2
- Step 5: Get 2 returns -1 (evicted)
- Step 6: Put (4,4) evicts key 1
- Step 7: Subsequent gets return appropriate values
Example 2
- Input: ["LRUCache", "put", "put", "get", "get", "put", "get"] [[2], [1, 10], [2, 20], [1], [2], [3, 30], [2]]
- Output: [null, null, null, 10, 20, null, 20]
- Explanation:
- Step 1: Create cache with capacity 2
- Step 2: Put (1,10) and (2,20)
- Step 3: Gets return both values
- Step 4: Put (3,30) evicts key 1
- Step 5: Get 2 still returns 20
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) access to cache entries
- The doubly linked list helps in maintaining the order of usage
- When an item is accessed, move it to the front of the linked list
- When cache is full, remove the item at the end of the linked list