Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: - LRUCache(capacity) Initialize the LRU cache with positive size capacity. - get(key) Return the value of the key if the key exists, otherwise return -1. - put(key, value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity.
Input: LRUCache cache = new LRUCache(2); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1
Output: 1, -1
Topics: hash-map, linked-list
Asked by: Amazon, Google, Microsoft, Meta, Bloomberg
Time complexity: O(1). Space complexity: O(n).