2020-08-27 06:34:40
LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
1. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
2. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity. Capacity indicates the maximum number of unique keys it can hold at a time.
NOTE: If you are using any global variables, make sure to clear them in the constructor.
Example -
LRUCache cache = new LRUCache(2);
cache.put(1, 24);
cache.put(2, 50);
cache.get(1); // returns 24
cache.put(3, 30); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 42); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 30
cache.get(4); // returns 42
Explanation -
First LRUCache is instantiated with capacity of 2. Then cache is initialized with (1, 1) and (2, 2) key-value pairs.
cache.get(1) returns value 24 which corresponds to key 1. Inserting (3, 30) pair evicts least recently used item i.e. with key 2.
Now there is no key 2, so cache.get(2) returns -1. Inserting (4, 42) evicts least recently used item with key 1.
Now cache contains values corresponding to keys 3 and 4. So cache.get(1) returns -1 while cache.get(3) and cache.get(4) returns corresponding values.
Topic : Maps
Asked in Amazon, Microsoft, Adobe, Citigroup
References ->
InterviewBit, LeetCode
Solution ->
GeeksforGeeks article 1, article 2
Join our Official Channel @cseinterview
968 views03:34