A simple and efficient implementation of a Least Recently Used (LRU) Cache using a hash map and a doubly linked list in Python. Designed for constant-time get and put operations.
- O(1) time complexity for both
getandput - Custom implementation of a doubly linked list
- Automatically evicts the Least Recently Used item when capacity is exceeded
- Easy-to-read internal structure for debugging and visualization
- Hash Map (
dict): For fast key lookup. - Doubly Linked List: Maintains access order.
- Head: Most Recently Used (MRU)
- Tail: Least Recently Used (LRU)
cache = LRUCache(2)
cache.put(1, 1) # Cache is {1=1}
print(cache)
cache.put(2, 2) # Cache is {2=2, 1=1}
print(cache)
cache.get(1) # Returns 1, Cache becomes {1=1, 2=2}
print(cache)
cache.put(3, 3) # Evicts key 2, Cache becomes {3=3, 1=1}
print(cache)
cache.get(2) # Returns -1 (not found)Initialize the cache with a given capacity.
Add a key-value pair to the cache.
If the key exists, update the value and mark it as recently used.
If capacity is exceeded, the least recently used item is evicted.
Return the value for the given key if it exists, and mark it as recently used.
Returns -1 if the key is not present.
Returns a string representation of the cache contents from MRU to LRU.
_add_to_front(node)β Inserts node right afterhead_remove(node)β Detaches node from the list_move_to_front(node)β Moves an existing node to the front_evict_from_back()β Removes and returns the LRU node
- Python 3.6+
This project is open-source and free to use under the MIT License.