1. Understand the Goal: The user wants a program that implements an LRU (Least Recently Used) cache.
-
Analyze the Requirements:
- What is an LRU Cache? It's a key-value store with a fixed capacity. When the capacity is exceeded, the item that hasn't been used for the longest time (least recently used) is evicted.
- Core Operations:
get(key): Retrieve a value. If present, it counts as "using" it (move to front). If absent, return -1 or null.
put(key, value): Add/Update a value. If present, update value and move to front. If absent, add to front. If at capacity, evict the LRU item (at the back) before adding.
- Performance Constraints: Standard requirements for a cache are O(1) time complexity for both
get and put operations.
-
Choose the Data Structure:
- Hash Map (Dictionary): Good for O(1) lookups by key.
- Doubly Linked List: Good for maintaining order. Adding/removing nodes at head or tail is O(1). Moving a node from the middle to the head is O(1) if we have a reference to it.
- Combination: A Hash Map mapping keys to Doubly Linked List Nodes. The List maintains the usage order (MRU -> LRU).
-
Language Selection: Python is a great choice for readability and has collections.OrderedDict which does exactly this under the hood. However, to demonstrate understanding of the algorithm (often asked in interviews), it's better to implement it from scratch using a Hash Map + Doubly Linked List. I will provide both:
- The "from scratch" implementation (educational/algorithmic).
- The "Pythonic" shortcut using
OrderedDict (pragmatic).
-
Drafting the "From Scratch" Solution (Python):
- Node Class: Needs
key, value, prev, next.
- LRUCache Class:
__init__(capacity): Initialize map, dummy head/tail (to simplify edge cases), size, capacity.
_remove(node): Helper to unlink a node.
_add(node): Helper to add right after head (MRU position).
get(key):
- Check map.
- If exists: move to front (remove + add), return value.
- Else: return -1.
put(key, value):
- Check map.
- If exists: update value, move to front.
- If new:
- Create node.
- Add to map.
- Add to list front.
- Increment size.
- If size > capacity: remove tail.prev (LRU), remove from map, decrement size.
-
Refining the Code (Self-Correction/Edge Cases):
- Head/Tail: Using dummy nodes
self.head and self.tail makes add and remove logic cleaner because we never deal with None pointers for actual data nodes.
- Map Management: When evicting, make sure to remove from the map using the node's key.
-
Drafting the "OrderedDict" Solution:
- Python's
OrderedDict has move_to_end(key) and popitem(last=False).
- This is very concise.
-
Structuring the Final Output:
- Start with a brief explanation of the logic (Hash Map + Doubly Linked List).
- Provide the "From Scratch" implementation (standard interview solution).
- Provide the "Python Standard Library" implementation (practical usage).
- Add comments explaining time complexity (O(1)).
-
Writing the Code (Mental Draft -> Actual Code):
-
Class Node:
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
-
Class LRUCache:
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = {} # map key -> node
# Dummy nodes
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node):
# Unlink
p, n = node.prev, node.next
p.next = n
n.prev = p
def _add(self, node):
# Add to front (after 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.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
lru = self.tail.prev
self._remove(lru)
del self.cache[lru.key]
-
Final Review:
- Did I handle the update case in
put? Yes, remove old, add new.
- Did I handle eviction correctly? Yes,
tail.prev is the LRU.
- Are both
get and put O(1)? Yes, hash map lookups are O(1), and pointer updates are O(1).
-
Constructing the response: Present the code clearly with explanations. (I will focus on Python as it is the most common language for this type of request, but the logic applies to Java/C++ too).
Here is a standard 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 in the linked list for fast access.
- 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 remain at the tail (end) for easy eviction.
Implementation (From Scratch)
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
Explanation of Logic
_add(node): When a node is added or accessed, it is placed right after the head. This signifies it is the Most Recently Used (MRU).
_remove(node): Disconnects the node from its neighbors.
get(key):
- If the key exists, we remove the node from its current position and add it to the front (making it MRU).
- If it doesn't exist, return -1.
put(key, value):
- If the key already exists, we remove the old node.
- We create a new node and add it to the front.
- If the cache size exceeds
capacity, we look at the node immediately before the tail (the Least Recently Used) and remove it from both the list and the hash map.
Python Shortcut (using OrderedDict)
If you are using Python in a production environment (or a non-interview setting), you can use the built-in collections.OrderedDict to achieve this with much less code.
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)