
Problem
Solution
Submissions
LRU Cache
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to implement an LRU (Least Recently Used) Cache. The cache should support get and put operations. When the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item. Both get and put operations should run in O(1) average time complexity.
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: put(1,1) - Cache: {1=1}. put(2,2) - Cache: {1=1, 2=2}. get(1) - Returns 1, Cache: {2=2, 1=1} (1 moved to end). put(3,3) - Capacity full, remove LRU(2), Cache: {1=1, 3=3}. get(2) - Returns -1 (not found).
Example 2
- Input: capacity = 1, operations = [put(2,1), get(2), put(3,2), get(2)]
- Output: [null, 1, null, -1]
- Explanation: put(2,1) - Cache: {2=1}. get(2) - Returns 1, Cache: {2=1}. put(3,2) - Capacity full, remove LRU(2), Cache: {3=2}. get(2) - Returns -1 (not found).
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 doubly linked list and hash table
- Hash table provides O(1) access to cache nodes
- Doubly linked list maintains the order of usage
- Most recently used items are at the tail of the list
- Least recently used items are at the head of the list
- When capacity is full, remove the head node before adding new node