LRU Cache - Problem
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity)- Initialize the LRU cache with positive size capacityint get(int key)- Return the value of the key if the key exists, otherwise return -1void put(int key, int value)- Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.
Input & Output
Example 1 — Basic LRU Operations
$
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]
💡 Note:
Cache capacity is 2. put(1,1), put(2,2) fills cache. get(1) returns 1. put(3,3) evicts key 2. get(2) returns -1 (evicted). put(4,4) evicts key 1. get(1) returns -1, get(3) returns 3, get(4) returns 4.
Example 2 — Single Capacity
$
Input:
capacity = 1, operations = [["put",2,1],["get",2],["put",3,2],["get",2],["get",3]]
›
Output:
[null,1,null,-1,2]
💡 Note:
With capacity 1, each put operation evicts the previous key. put(2,1), get(2) returns 1, put(3,2) evicts key 2, get(2) returns -1, get(3) returns 2.
Example 3 — Update Existing Key
$
Input:
capacity = 2, operations = [["put",1,1],["put",2,2],["put",1,10],["get",1],["get",2]]
›
Output:
[null,null,null,10,2]
💡 Note:
put(1,1), put(2,2), then put(1,10) updates existing key 1 to value 10 and moves it to most recent. get(1) returns 10, get(2) returns 2.
Constraints
- 1 ≤ capacity ≤ 3000
- 0 ≤ key ≤ 104
- 0 ≤ value ≤ 105
- At most 2 × 104 calls will be made to get and put
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code