I need to design and implement an LRU cache. The user didn't specify a programming language, but they might be looking for both an algorithm and code. I'll aim for memory efficiency and O(1) operations, likely using a hashmap in combination with a doubly-linked list.
I could present a conceptual design and code examples in common languages like Python or C++. I'll focus on Python for memory efficiency, potentially using __slots__ or collections.OrderedDict.Optimizing Memory for LRU Cache
I’m considering how to enhance memory efficiency in the LRU cache. I could use double-linked nodes for keys and values while maintaining a dictionary to associate keys with nodes, which is pretty standard.
To save memory, I might implement __slots__ in the Node class to eliminate the need for __dict__. I’ll define essential functions like get(key) and put(key, value) along with a capacity parameter. For eviction, I’ll remove the least recently used item when capacity exceeds. I'll show the code to implement this in Python.Designing a Circular Doubly-Linked List
I’m focusing on maintaining a circular doubly-linked list with a single sentinel node and no dictionary entry, which is quite common.
In my implementation, I'll define the Node class with __slots__ to efficiently handle memory. The head sentinel's prev will point to the least recently used (LRU) node, and next will point to the most recently used (MRU) node. Whenever we read or write a key, we'll move that node to head.next. For eviction, I'll simply take the tail as head.prev.Implementing LRU Cache Functions
I’m drafting the pseudo-code for my LRU cache implementation. I'll define methods to insert nodes at the front, remove them, move nodes to the front, and pop the least recently used (LRU) node.
In the constructor, I’ll set up the head sentinel node and initialize the map and capacity. The get(key) method will retrieve the node and move it to the front, while the put(key, value) method will handle updates and evictions if the capacity is exceeded.
To enhance memory efficiency, using __slots__ and maintaining a single sentinel node are key strategies.Considering LRU Cache Implementation
The user might be looking for concurrency safety, although they didn't specify it. They mentioned "O(1) operations," and I'm aware that while Python dictionaries typically offer O(1) on average, there are rare cases where it can be O(n). Since the user hasn’t selected a language, I'll provide a generic algorithm alongside a Python implementation, noting that it can be adapted to others as needed.
I could highlight that while collections.OrderedDict is effective, customizing the implementation might enhance memory efficiency. I'll begin by outlining the necessary data structures and their complexities before providing the code in Markdown format, keeping it concise and focused. You can get O(1) get/put and good memory efficiency with:
a hash table: key -> node
an intrusive doubly-linked list of nodes that holds (key, value)
one sentinel (“dummy”) node to avoid None checks
__slots__ to reduce per-node memory (in Python)
Core idea
Hash map gives O(1) lookup of the node for a key.
Doubly-linked list keeps items in recency order:
Head side = most recently used (MRU)
Tail side = least recently used (LRU)
On every get or put, move the node to the front (MRU).
When at capacity and inserting a new key, evict the tail node (LRU).
Python implementation
python
class _Node:
__slots__ = ("key", "value", "prev", "next") # saves memory vs __dict__
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.map = {} # key -> _Node
# Sentinel node for a circular doubly-linked list
self._sentinel = _Node()
self._sentinel.prev = self._sentinel
self._sentinel.next = self._sentinel
# --- internal list helpers (all O(1)) ---
def _insert_front(self, node: _Node) -> None:
"""Insert node right after sentinel (MRU position)."""
first = self._sentinel.next
node.prev = self._sentinel
node.next = first
first.prev = node
self._sentinel.next = node
def _remove_node(self, node: _Node) -> None:
"""Unlink node from the list."""
prev_node = node.prev
next_node = node.next
prev_node.next = next_node
next_node.prev = prev_node
def _move_to_front(self, node: _Node) -> None:
"""Mark node as most recently used."""
self._remove_node(node)
self._insert_front(node)
def _pop_lru(self) -> _Node | None:
"""Remove and return least recently used node (tail)."""
tail = self._sentinel.prev
if tail is self._sentinel: # list is empty
return None
self._remove_node(tail)
return tail
# --- public API ---
def get(self, key):
"""Return value for key or None if not found. O(1)."""
node = self.map.get(key)
if node is None:
return None
self._move_to_front(node)
return node.value
def put(self, key, value) -> None:
"""Insert or update key with value. O(1)."""
node = self.map.get(key)
if node is not None:
# Update existing
node.value = value
self._move_to_front(node)
return
# Insert new
if len(self.map) >= self.capacity:
# Evict LRU
lru = self._pop_lru()
if lru is not None:
del self.map[lru.key]
new_node = _Node(key, value)
self._insert_front(new_node)
self.map[key] = new_node
def __contains__(self, key) -> bool:
return key in self.map
def __len__(self) -> int:
return len(self.map)
Why this is memory-efficient
Each cache entry is a single _Node object storing:
key, value, prev, next
__slots__ removes the per-object __dict__, saving memory per node.
Only one sentinel node is allocated to manage the list structure.
The hash table stores references to existing nodes; keys and values are not duplicated.
This design generalizes easily to other languages (C++, Java, etc.) by combining:
a hash map: unordered_map<K, Node*> or HashMap<K, Node>