Design a cache for at most capacity keys. get(key) returns the key's value, or -1 if it is not there. put(key, value) adds the key or replaces its value; if that makes too many keys, the key used longest ago is dropped. Both have to run in O(1). Our calls, capacity 2: put(4, 40), put(7, 70), put(4, 45), put(9, 90), get(7), get(4) — get(7) returns -1, get(4) returns 45.
input
Calls one after another: LRUCache(capacity) makes an empty cache for capacity keys, then get(key) and put(key, value) in any order. When a new key does not fit, put evicts the key used least recently; a get or a put of a key uses it.
returns
get(key) returns the value of key, or −1 when it is not in the cache; put returns nothing (null in the output). LeetCode wants each call in O(1).
constraints
2 ≤ calls ≤ 2000
1 ≤ capacity ≤ 100
0 ≤ key ≤ 1000
0 ≤ value ≤ 10⁵
our 10 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
timer
switch language →
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key, value)
*/
Ctrl ↵
format
reset
saved in this browser
10 tests · limit 3 s
Stuck?
See the solution run step by step on our example, then why it works and its complexity.