In a Meta-style system such as Facebook Feed, recently accessed items are often kept in a fixed-size cache. Design and implement an LRU (Least Recently Used) cache that supports get and put in O(1) average time.
You must implement a cache with a fixed positive capacity:
get(key) returns the value associated with key if it exists, otherwise returns -1.put(key, value) inserts or updates the key-value pair.get or put on an existing key makes that key the most recently used.Implement a class LRUCache with:
LRUCache(capacity: int)get(key: int) -> intput(key: int, value: int) -> NoneUse integer keys and values.
Example 1:
capacity = 2, operations = [put(1,1), put(2,2), get(1), put(3,3), get(2)][null, null, 1, null, -1]1 becomes recently used after get(1), so key 2 is evicted when key 3 is inserted.Example 2:
capacity = 1, operations = [put(1,10), put(2,20), get(1), get(2)][null, null, -1, 20]2 evicts 1.1 <= capacity <= 30000 <= key, value <= 10^92 * 10^5 calls to get and putget and put should run in O(1) average time