Data Structures · Visualization
LRU Cache: Get
LRU Cache
Getting a value looks it up instantly using the hash table, and — because accessing an item counts as 'using' it — also moves that item to the front of the recency-ordered linked list, marking it as the most recently used. Time: O(1). Space: O(1) per operation.
Big-O: get / put both O(1).
LRU Cache: Get
LRU CacheGetting a value looks it up instantly using the hash table, and — because accessing an item counts as 'using' it — also moves that item to the front of the recency-ordered linked list, marking it as the most recently used. If the key doesn't exist, the get simply reports a miss.
How Get Works
- Look up the key in the hash table.
- If the key doesn't exist, return 'not found' (a cache miss).
- If it exists, retrieve its value and its node in the linked list.
- Move that node to the front of the linked list (most recently used position).
- Return the value.
Get Worked Example
Input: Get(1) on cache [2:B, 1:A] (front to back)
- Look up key 1 in the hash table → found, value A
- Move node 1 to the front of the linked list
Output: Returns A; cache order becomes [1:A, 2:B]
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: get key=1Behind 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.
Get Time & Space Complexity
When to Use Get
- Fetching a cached web page while marking it as recently viewed
- Reading a cached database query result
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.