33Implement an LRU cache
mediumAbout 35 minutesCodingcachinghash-maplinked-listdesign
Problem
Implement an LRUCache class with a fixed capacity. When it is full and a new key is added, it evicts the least recently used key.
get(key): return the value, or-1if the key is not there. Reading a key makes it the most recently used.put(key, value): insert or update the key, making it the most recently used. If this pushes the size overcapacity, evict the least recently used key.
const cache = new LRUCache(2);
cache.put(1, "one");
cache.put(2, "two");
cache.get(1); // "one" (1 is now the most recent)
cache.put(3, "three"); // evicts 2
cache.get(2); // -1Requirements
- Both
getandputrun in O(1) on average. - Updating an existing key never evicts anything.
- Expose
size(the number of keys stored).
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthrough
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
A JavaScript Map iterates its keys in insertion order. If you delete a key and set it again, it moves to the end. So the end of the map is "most recent" and the first key is "least recent".
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 5 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.