The user wants a memory-efficient Least Recently Used (LRU) cache with O(1) time complexity for both get and put operations.
1. Understanding the Requirements:
LRU Cache: Evicts the least recently used item when the cache is full.
O(1) Operations:get(key) and put(key, value) must be constant time.
Memory Efficient: Minimize overhead. This usually means avoiding excessive object creation or sticking to primitive data structures where possible, though in Python, OrderedDict is the standard idiomatic solution, and a custom Double Linked List + HashMap is the standard algorithmic interview solution.
2. Standard Solution (Interview Style):
Data Structures:
HashMap (Dictionary): Maps Key to Node. Allows O(1) access to the node.
Double Linked List (DLL): Maintains the usage order.
Head: Most recently used.
Tail: Least recently used.
Operations:
get(key):
Check map. If missing, return -1.
If found, move node to head (remove from current position, add to head).
Return value.
put(key, value):
Check map.
If exists: Update value, move to head.
If not exists:
Create new node, add to head, add to map.
If size > capacity: Remove tail node, remove from map.
__slots__: In Python, classes usually carry a __dict__ which consumes a significant amount of memory per instance. Using __slots__ on the Node class prevents the creation of a dynamic attribute dictionary and fixes the memory footprint, which is significantly more memory-efficient for thousands of nodes.
OrderedDict: Python's collections.OrderedDict is implemented in C (in modern Python versions) and handles the move-to-end logic efficiently. It is generally more memory-efficient and faster than a pure Python implementation of a linked list because the overhead is handled at the C level. However, strictly speaking, the question asks for a "memory-efficient LRU cache," and often these coding challenges want the underlying implementation logic shown. But OrderedDict is the practical answer.
Decision: I will provide the Double Linked List + HashMap implementation using __slots__ as the "Algorithmic/Interview" solution because it demonstrates the O(1) mechanics clearly and __slots__ addresses the memory constraint. I will also mention OrderedDict as the Pythonic alternative.
4. Drafting the Code:
Node Class:
Needs key, value, prev, next.
Use __slots__ to save memory.
LRU Cache Class:
capacity: integer.
cache: Dictionary {key: Node}.
head, tail: Dummy nodes (sentinels) to simplify edge case handling (empty list, single node). This removes if node.prev is None checks, making code cleaner and slightly faster.
Helper Methods (Private):
_remove(node): Disconnect node from list.
_add(node): Add node right after head.
Public Methods:
get(key): Lookup in dict. If found, _remove(node) and _add(node).
put(key, value):
If exists: _remove(old).
Create new node, _add(new), store in dict.
If len > cap: Remove node before tail (tail.prev), delete from dict.
5. Refining the Logic (Self-Correction during drafting):
Wait, do I need to store the key in the Node? Yes, absolutely. When evicting the tail, I need to know which key to delete from the hashmap. If I just have the node, I can't remove the entry from the dictionary without the key.
Sentinel Nodes:head and tail initialized with None values. head.next = tail, tail.prev = head. Real data goes between them.
6. Writing the Implementation (Mental Draft):
python
class Node:
__slots__ = 'key', 'value', 'prev', 'next' # Memory optimization
def __init__(self, k, v):
self.key = k
self.value = v
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = {}
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node):
p, n = node.prev, node.next
p.next = n
n.prev = p
def _add(self, node): # Add to front (head)
p, n = self.head, self.head.next
p.next = node
node.prev = p
node.next = n
n.prev = node
def get(self, key):
if key in self.cache:
node = self.cache[key]
self._remove(node)
self._add(node)
return node.value
return -1
def put(self, key, value):
if key in self.cache:
self._remove(self.cache[key])
node = Node(key, value)
self._add(node)
self.cache[key] = node
if len(self.cache) > self.cap:
lru = self.tail.prev
self._remove(lru)
del self.cache[lru.key]
7. Final Review:
O(1)? Yes. HashMap is O(1). List pointer ops are O(1).
Memory Efficient? Yes, __slots__ is the key differentiator here compared to a standard class. Sentinels remove branching overhead.
Readability: It's decent. Comments are needed.
8. Alternative:functools.lru_cache.
Python has a built-in decorator. It's highly optimized C code.
However, usually "Create an LRU cache" implies implementing the data structure logic, not just importing a library. I will provide the implementation first, and note the built-in as a "production ready" alternative.
9. Formatting:
Present the solution clearly.
Explain why it's O(1) (Hash Map + DLL).
Explain why it's memory efficient (__slots__).
Let's structure the response:
The Approach: Explain the Hash Map + Doubly Linked List architecture.
The Code: Provide the Python class.
Memory Optimization: Detail the use of __slots__.
Usage Example: Show it running.
Alternative: Mention OrderedDict.
(Self-Correction): Make sure to handle the case where put updates an existing key. In my mental draft:
if key in self.cache: self._remove(self.cache[key])
Then create new node and add.
This works perfectly.
One detail: The prompt asks for memory efficiency.
Using dict + doubly linked list is the standard.
Is there a way to use less memory?
If we use collections.OrderedDict, the overhead is lower in Python 3.7+ because the dict implementation is compact and the node logic is internal C.
However, __slots__ on a custom class is often competitive or better if the number of attributes is small (4), whereas an OrderedDict might carry more metadata overhead in pure Python (though C-optimized OrderedDict is fast).
I will stick to the Custom Node + __slots__ because it demonstrates the algorithm specifically requested.
Let's finalize the code structure.
python
class Node:
__slots__ = ('key', 'val', 'prev', 'next')
...
This looks good.
Wait, strict memory efficiency might also imply implementing an LRU without a linked list if we were in C (using a hash table array and moving indices). But in Python, a list of indices or a custom array is often slower and not necessarily more memory efficient than __slots__. The Double Linked List is the canonical answer.
Final check on logic:
Get:
Key exists: remove node, add to front (MRU), return val.
Key not exists: return -1.
Put:
Key exists: remove old node.
Create new node.
Add to front (MRU).
Map key -> new node.
If size > cap:
Remove node prev to tail (LRU).
Delete key from map.
Correct.
Let's write it out.
Here is a memory-efficient implementation of an LRU (Least Recently Used) cache in Python.
The Data Structure Strategy
To achieve O(1) time complexity for both get and put operations, we combine two data structures:
Hash Map (Dictionary): Maps the key to the specific Node in the linked list. This allows us to find the item instantly without traversing.
Doubly Linked List: Maintains the order of elements.
Head: Most recently used item.
Tail: Least recently used item.
To ensure memory efficiency, we utilize Python's __slots__ feature for the Node class. This prevents the creation of a dynamic __dict__ for every single node, significantly reducing the RAM overhead (often by 3x-5x) when the cache stores millions of items.
The Implementation
python
class Node:
"""
A Doubly Linked List Node optimized for memory usage.
Using __slots__ prevents the creation of a per-instance __dict__,
saving significant memory for large caches.
"""
__slots__ = ['key', 'val', 'prev', 'next']
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = {} # Map key -> Node
# Initialize dummy head and tail nodes.
# These allow us to add/remove nodes without checking for None edges.
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node: Node):
"""Removes a node from the linked list."""
prev_node = node.prev
next_node = node.next
prev_node.next = next_node
next_node.prev = prev_node
def _add(self, node: Node):
"""Adds a node right after the head (Most Recently Used position)."""
head_next = self.head.next
self.head.next = node
node.prev = self.head
node.next = head_next
head_next.prev = node
def get(self, key: int) -> int:
"""
Returns the value if key exists.
Moves the node to the front (MRU) because it was just accessed.
Time: O(1)
"""
if key in self.cache:
node = self.cache[key]
# Move to front: remove from current spot, add to head
self._remove(node)
self._add(node)
return node.val
return -1
def put(self, key: int, value: int) -> None:
"""
Inserts/Updates the key.
If full, removes the LRU node (node before tail).
Time: O(1)
"""
if key in self.cache:
# If key exists, update value and move to front
old_node = self.cache[key]
self._remove(old_node)
# Create new node and add to front
new_node = Node(key, value)
self._add(new_node)
self.cache[key] = new_node
# If over capacity, remove the LRU item (item before tail)
if len(self.cache) > self.capacity:
lru_node = self.tail.prev
self._remove(lru_node)
del self.cache[lru_node.key]
# --- Usage Example ---
if __name__ == "__main__":
# Initialize cache with capacity 2
lru = LRUCache(2)
lru.put(1, 1) # Cache: {1=1}
lru.put(2, 2) # Cache: {1=1, 2=2}
print(lru.get(1)) # Returns 1. Cache: {2=2, 1=1} (1 is now MRU)
lru.put(3, 3) # Evicts key 2. Cache: {1=1, 3=3}
print(lru.get(2)) # Returns -1 (not found)
lru.put(4, 4) # Evicts key 1. Cache: {3=3, 4=4}
print(lru.get(1)) # Returns -1 (not found)
print(lru.get(3)) # Returns 3
print(lru.get(4)) # Returns 4
Key Logic Explained
_remove(node): Disconnects a node from the list by linking its neighbors directly to each other.
_add(node): Inserts a node immediately after the self.head. This marks it as the "Most Recently Used".
Eviction Policy: When the capacity is exceeded, we look at self.tail.prev. Since the tail is a dummy node, the node immediately preceding it is the Least Recently Used (LRU).
Why this is Memory Efficient
In standard Python classes, attributes are stored in a dictionary (__dict__). For a class with 4 attributes, the dictionary overhead (hash table buckets, keys, etc.) is often larger than the data itself.
By defining __slots__ = ['key', 'val', 'prev', 'next'], Python allocates fixed space for exactly these 4 pointers. This removes the per-instance dictionary overhead, which is crucial when the cache contains hundreds of thousands or millions of entries.