Hash Map (Dictionary): Maps key to the Node in the linked list. Access time: O(1).
Doubly Linked List: Maintains the order.
Head: Most Recently Used (MRU).
Tail: Least Recently Used (LRU).
Why Doubly Linked? We need to remove a node from the middle and insert it at the head efficiently. With a DLL, removal is O(1) if we have the pointer to the node (which the Hash Map provides).
Design the Class Structure (Python example):
Node class:
key, val (data)
prev, next (pointers)
LRUCache class:
capacity (int)
cache (dict: key -> Node)
head, tail (dummy nodes to handle edge cases easily)
Algorithm for Operations:
_remove(node): Helper
Unlink node.prev and node.next.
_add(node): Helper (Add to front/MRU)
Insert node right after head.
get(key):
Check if key in cache.
If no, return -1.
If yes:
Get node.
Update usage: Remove node from current position, add to front.
Return node.val.
put(key, value):
Check if key in cache.
Case 1: Update existing
Get node.
Update node.val.
Update usage: Remove node, add to front.
Case 2: Insert new
Create new_node.
Add to cache.
Add to front.
Check size: If len(cache) > capacity:
Identify LRU (node before tail).
Remove LRU from list.
Remove LRU key from cache.
Refinement / Language Choice:
Python is the most common language for these explanations due to readability, but using OrderedDict from collections is the "Pythonic" shortcut. However, implementing the DLL manually is usually what's expected in an interview to demonstrate understanding.
I will provide:
The manual implementation (Hash Map + DLL) because it explains how it works.
The Python OrderedDict shortcut because it's practical.
Drafting the Code (Mental or Scratchpad):
python
class Node:
def __init__(self, k, v):
self.key = k
self.val = v
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = {}
# Dummy head and tail
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 (right after head)
# head <-> node <-> old_head_next
old_next = self.head.next
self.head.next = node
node.prev = self.head
node.next = old_next
old_next.prev = node
def get(self, key):
if key in self.cache:
node = self.cache[key]
self._remove(node)
self._add(node)
return node.val
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:
# Evict LRU (node before tail)
lru = self.tail.prev
self._remove(lru)
del self.cache[lru.key]
Wait, in put, if I update an existing key, I shouldn't check capacity because the size didn't increase.
Correction: The logic flow if key in cache: remove handles the size implicitly. If key exists, I remove the old node. Then I add the new node. Size stays same. If key doesn't exist, size increases. Then check cap. The draft code logic actually handles this correctly because the remove happens before the add and cache insertion.
Formatting: Use code blocks, comments, and clear variable names. Add type hinting for clarity.
Alternative Languages: Should I write in Java or C++? The prompt is generic. Python is usually the safest bet for "Write a program". I will stick to Python but write it clearly enough to be translated.
(Self-Correction on the _add helper): Wait, if I add a node that was just removed, I need to make sure pointers are handled.
In _add:
self.head.next.prev = nodeself.head.next = node
Actually, let's be precise.
Current: head <-> nxt
Target: head <-> node <-> nxt
node.prev = head
node.next = head.next (which is nxt)
nxt.prev = node (Wait, nxt is currently pointed to by head.next. If I change head.next first, I lose nxt. Order matters).
Correct order:
node.prev = head
node.next = head.next
head.next.prev = node (Update nxt's prev pointer before changing head.next? No, head.next is still nxt. So this is valid).
head.next = node
Let's re-verify the "Right after head" logic.
self.head.next.prev = node -> This modifies the dummy node nxt to point back to node.
self.head.next = node -> This modifies dummy head to point to node.
Yes, this is correct.
Let's finalize the Python code.
python
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = {} # Map key to Node
# Dummy head and tail nodes to avoid edge cases
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, 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):
"""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:
if key in self.cache:
node = self.cache[key]
# Since we accessed it, move it to the front (MRU)
self._remove(node)
self._add(node)
return node.value
return -1
def put(self, key: int, value: int) -> None:
if key in self.cache:
# If key exists, update value and move to front
self._remove(self.cache[key])
node = Node(key, value)
self._add(node)
self.cache[key] = node
if len(self.cache) > self.capacity:
# Evict the LRU (the node before the tail)
lru_node = self.tail.prev
self._remove(lru_node)
del self.cache[lru_node.key]
This looks complete. I will present this solution. I will also mention the OrderedDict as a secondary "Pythonic" solution.
Final Polish: Ensure comments explain the why.
Why DLL? O(1) removal/insertion.
Why Hash Map? O(1) lookup.
Why Dummy Nodes? Simplifies null checks.
This thought process covers understanding requirements, selecting algorithms, data structure design, implementation details, edge case handling, and optimization.
Here is a complete implementation of an LRU Cache in Python.
To achieve O(1) time complexity for both get and put operations, this implementation combines two data structures:
Hash Map (Dictionary): Stores keys and maps them to their corresponding nodes for fast lookups.
Doubly Linked List: Maintains the order of elements. The most recently used items are moved to the head (front), and the least recently used items naturally settle at the tail (end).
The Code
python
class Node:
"""
A Doubly Linked List Node.
"""
def __init__(self, key, value):
self.key = key
self.value = value
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.
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, 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):
"""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:
if key in self.cache:
node = self.cache[key]
# Since we accessed it, move it to the front (MRU)
self._remove(node)
self._add(node)
return node.value
return -1
def put(self, key: int, value: int) -> None:
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]
# --- Example Usage ---
if __name__ == "__main__":
lru = LRUCache(2) # Capacity is 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
How It Works
Initialization: We create a Hash Map and a Doubly Linked List with head and tail pointers.
get(key):
If the key exists in the map, we retrieve the node.
We remove the node from its current position in the list and re-insert it right after the head. This marks it as "Most Recently Used" (MRU).
Returns the value.
put(key, value):
If the key already exists, we remove the old node from the list.
We create a new node, add it to the map, and insert it right after the head (MRU position).
Eviction Policy: If the map size exceeds the capacity, we look at the node immediately preceding the tail. This is the "Least Recently Used" (LRU) node. We remove it from the list and delete it from the map.
Alternative: Python OrderedDict
If you are using Python in a production environment (not an interview setting), you can use the built-in collections.OrderedDict for a much shorter implementation:
python
from collections import OrderedDict
class LRUCacheShort(OrderedDict):
def __init__(self, capacity: int):
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self:
return -1
self.move_to_end(key) # Moves to the right end (MRU)
return self[key]
def put(self, key: int, value: int) -> None:
if key in self:
self.move_to_end(key)
self[key] = value
if len(self) > self.capacity:
self.popitem(last=False) # Pops from left end (LRU)