Sitemap
Sagar Hande

Sagar Hande

I'm a Software Engineer based in India.

LRU Cache Implementation in Python

2 min readFeb 3, 2025

Below is a Python implementation of an LRU Cache using a Python
Implementation:

Get Sagar Hande’s stories in your inbox

Join Medium for free to get updates from this writer.

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 = {} # Hash map to store key -> Node mapping
self.head = Node(0, 0) # Dummy head node
self.tail = Node(0, 0) # Dummy tail node
self.head.next = self.tail
self.tail.prev = self.head


def _remove(self, node: Node):
"""Remove 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_to_front(self, node: Node):
"""Add a node to the front (right after the head) of the linked list."""
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node

def get(self, key: int) -> int:
"""Get the value of the key if it exists in the cache, otherwise return -1."""
if key in self.cache:
node = self.cache[key]
self._remove(node) # Remove the node from its current position
self._add_to_front(node) # Move it to the front (most recently used)
return node.value
return -1

def put(self, key: int, value: int) -> None:
"""Add or update the value of the key in the cache."""
if key in self.cache:
# If the key already exists, update its value and move it to the front
node = self.cache[key]
node.value = value
self._remove(node)
self._add_to_front(node)
else:
# If the key doesn't exist, create a new node and add it to the cache
if len(self.cache) >= self.capacity:
# If the cache is full, remove the least recently used node (tail.prev)
lru_node = self.tail.prev
self._remove(lru_node)

del self.cache[lru_node.key] # Remove it from the cache
new_node = Node(key, value)
self.cache[key] = new_node
self._add_to_front(new_node)

def __repr__(self):
"""Helper method to visualize the cache."""
result = []
current = self.head.next
while current != self.tail:
result.append(f"({current.key}: {current.value})")
current = current.next
return " -> ".join(result)

if __name__ == "__main__":
# Example usage:
lru_cache = LRUCache(2)
lru_cache.put(1, 1) # Cache is {1=1}
lru_cache.put(2, 2) # Cache is {1=1, 2=2}
print(lru_cache.get(1)) # Returns 1, Cache is {2=2, 1=1}
lru_cache.put(3, 3) # LRU key was 2, evicts key 2, Cache is {1=1, 3=3}
print(lru_cache.get(2)) # Returns -1 (not found)
lru_cache.put(4, 4) # LRU key was 1, evicts key 1, Cache is {3=3, 4=4}
print(lru_cache.get(1)) # Returns -1 (not found)
print(lru_cache.get(3)) # Returns 3, Cache is {4=4, 3=3}
print(lru_cache.get(4)) # Returns 4, Cache is {3=3, 4=4}

--

--

Sagar Hande
Sagar Hande

Written by Sagar Hande

I'm a Software Engineer based in India.