LRU Cache
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 sizecapacity.int get(int key)— Return the value of thekeyif the key exists, otherwise return-1.void put(int key, int value)— Update the value of thekeyif the key exists. Otherwise, add thekey-valuepair to the cache. If the number of keys exceeds thecapacityfrom this operation, evict the least recently used key.
The functions get and put must each run in O(1) average 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 cache = new LRUCache(2);
cache.put(1, 1); // cache is {1=1}
cache.put(2, 2); // cache is {1=1, 2=2}
cache.get(1); // return 1
cache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
cache.get(1); // return -1 (not found)
cache.get(3); // return 3
cache.get(4); // return 4
Examples
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: After put(1,1) and put(2,2), the cache holds {1=1, 2=2}. get(1) returns 1 and makes key 1 most recent. put(3,3) evicts key 2 (least recently used). get(2) returns -1. put(4,4) evicts key 1. get(1) returns -1, get(3) returns 3, get(4) returns 4.
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.
Optimal Complexity
Time
O(1)
Space
O(capacity)
Practice this problem with an AI interviewer
TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.
Start a free interview