Data Structures · Visualization
LRU Cache: Put
LRU Cache
Putting a value either updates an existing key or adds a new one, always moving the affected item to the front (most recently used). Time: O(1). Space: O(1) per operation.
Big-O: get / put both O(1).
LRU Cache: Put
LRU CachePutting a value either updates an existing key or adds a new one, always moving the affected item to the front (most recently used). If adding a brand-new key would push the cache over its capacity, the item at the very back of the list (the least recently used one) is evicted first to make room.
How Put Works
- Check if the key already exists in the hash table.
- If it exists, update its value and move its node to the front of the linked list.
- If it doesn't exist, create a new node, add it to the front of the linked list, and add it to the hash table.
- If adding the new node pushed the cache size over capacity, remove the node at the back of the list and remove its key from the hash table.
Put Worked Example
Input: Put(3,C) on a full cache [1:A, 2:B] with capacity 2
- Key 3 doesn't exist — create new node 3:C
- Add it to the front: [3:C, 1:A, 2:B]
- Cache size (3) exceeds capacity (2) — remove the back node (2:B)
Output: Final cache: [3:C, 1:A] (2:B was evicted)
Press ▶ Run to watch it step by step.
from collections import OrderedDict
class LRUCache:
def __init__(self, cap):
self.cap = cap
self.map = OrderedDict()
def get(self, key):
if key not in self.map:
return -1
self.map.move_to_end(key) # most recent
return self.map[key]
def put(self, key, value):
if key in self.map:
self.map.move_to_end(key)
self.map[key] = value
if len(self.map) > self.cap:
self.map.popitem(last=False) # evict LRU
# example: put value=CBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Put Time & Space Complexity
When to Use Put
- Storing a newly fetched web page in the browser cache
- Caching the result of an expensive computation or database query
- Managing limited memory in embedded or resource-constrained systems
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.