Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.int get(int key) Return the value of the key if the key exists, otherwise return -1.void put(int key, int 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.
Example 1:
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Constraints:
1 <= capacity <= 30000 <= key <= 1040 <= value <= 1052 * 105 calls will be made to get and put.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a small desk with a strict limit on how many items can fit on it at one time. The brute force strategy involves searching through your entire collection of items from scratch every time someone asks for something or hands you a new piece of work.
Here's how the algorithm would work step-by-step:
class LRUCache:
def __init__(self, capacity: int):
self.cache_capacity = capacity
self.desk_collection = []
self.storage_room = {}
def get(self, key: int) -> int:
# We search the desk collection linearly to find and refresh the accessed item
for item_index, item_pair in enumerate(self.desk_collection):
if item_pair[0] == key:
found_pair = self.desk_collection.pop(item_index)
self.desk_collection.append(found_pair)
return found_pair[1]
if key in self.storage_room:
retrieved_value = self.storage_room[key]
if len(self.desk_collection) >= self.cache_capacity:
oldest_item = self.desk_collection.pop(0)
self.storage_room[oldest_item[0]] = oldest_item[1]
self.desk_collection.append([key, retrieved_value])
del self.storage_room[key]
return retrieved_value
return -1
def put(self, key: int, value: int) -> None:
# Existing keys must be updated in place and moved to the most recent position
for item_index, item_pair in enumerate(self.desk_collection):
if item_pair[0] == key:
self.desk_collection.pop(item_index)
self.desk_collection.append([key, value])
return
if key in self.storage_room:
self.storage_room[key] = value
self.get(key)
return
if len(self.desk_collection) >= self.cache_capacity:
oldest_item = self.desk_collection.pop(0)
self.storage_room[oldest_item[0]] = oldest_item[1]
self.desk_collection.append([key, value])To build a lightning-fast memory storage system that forgets its oldest items when it gets too full, we combine a quick-reference directory with a flexible chain of items. This clever combination lets us find, add, and remove items almost instantly, no matter how many things we are storing.
Here's how the algorithm would work step-by-step:
class DoublyLinkedListNode:
def __init__(self, cache_key=0, cache_value=0):
self.cache_key = cache_key
self.cache_value = cache_value
self.previous_node = None
self.next_node = None
class LRUCache:
def __init__(self, maximum_capacity: int):
self.maximum_capacity = maximum_capacity
self.cache_directory = {}
self.head_sentinel = DoublyLinkedListNode()
self.tail_sentinel = DoublyLinkedListNode()
self.head_sentinel.next_node = self.tail_sentinel
self.tail_sentinel.previous_node = self.head_sentinel
def _remove_node(self, target_node):
previous_item = target_node.previous_node
following_item = target_node.next_node
previous_item.next_node = following_item
following_item.previous_node = previous_item
def _add_node_to_front(self, target_node):
following_item = self.head_sentinel.next_node
self.head_sentinel.next_node = target_node
target_node.previous_node = self.head_sentinel
target_node.next_node = following_item
following_item.previous_node = target_node
def _move_node_to_front(self, target_node):
self._remove_node(target_node)
self._add_node_to_front(target_node)
def _pop_tail_node(self):
oldest_node = self.tail_sentinel.previous_node
self._remove_node(oldest_node)
return oldest_node
def get(self, cache_key: int) -> int:
# Look up instantly in our master index to find the exact item location.
if cache_key not in self.cache_directory:
return -1
target_node = self.cache_directory[cache_key]
self._move_node_to_front(target_node)
return target_node.cache_value
def put(self, cache_key: int, cache_value: int) -> void:
# Update existing items and refresh their position to the front of the line.
if cache_key in self.cache_directory:
target_node = self.cache_directory[cache_key]
target_node.cache_value = cache_value
self._move_node_to_front(target_node)
return
# Evict the oldest item at the back when capacity is fully exhausted.
if len(self.cache_directory) >= self.maximum_capacity:
oldest_node = self._pop_tail_node()
del self.cache_directory[oldest_node.cache_key]
new_node = DoublyLinkedListNode(cache_key, cache_value)
self._add_node_to_front(new_node)
self.cache_directory[cache_key] = new_node| Case | How to Handle |
|---|---|
| Cache capacity is set to 1 | The least recently used item must be evicted on every subsequent insertion after the first. |
| Accessing or updating an existing key | The existing node is moved to the most recently used position without changing the cache capacity. |
| Inserting a key that already exists with a new value | Update the value and promote the node to the head of the doubly linked list. |
| Cache reaches full capacity and a new unique key is inserted | Remove the tail node from the linked list and delete it from the hash map before adding the new item. |
| Retrieving a key that does not exist in the cache | Return negative one or the standard language-specific absence indicator immediately. |
| Zero or negative values for capacity | Initialize a conditional check to handle invalid capacities gracefully by throwing an error or ignoring operations. |
| Keys and values include extreme boundary integers like negative numbers or zero | The hash map uses exact key matching and the linked list stores generic pointers, making key-value identity agnostic to number signs. |
| High frequency of continuous gets on the same key | Repeatedly moving the same node to the front remains an O(1) operation due to direct pointer manipulation. |