Solution: LRU Cache
Explore how to build an LRU cache class that efficiently manages key-value pairs with constant time access. Understand the tradeoffs between a naive linked-list approach and an optimized solution combining a doubly linked list and hash map. Learn to implement cache eviction by removing the least recently used item once capacity is reached, improving your ability to handle caching challenges in coding interviews.
Statement
Implement an LRU cache class with the following functions:
-
LRU(capacity): Initializes an LRU cache with the capacity size.
-
Set(key, value): Adds a new key-value pair or updates an existing key with a new value.
-
Get(key): Returns the value of the key, or if the key does not exist.
If the number of keys has reached the cache capacity, evict the least recently used key and then add the new key.
As caches use relatively expensive, faster memory, they are not designed to store very large data sets. Whenever the cache becomes full, we need to evict some data from it. There are several caching algorithms to implement a cache eviction policy. LRU is a very simple and commonly used algorithm. The core concept of the LRU algorithm is to evict the oldest data from the cache to accommodate more data.
Constraints:
- capacity