LRU Cache
Design an LRU cache with O(1) get and put.
Pattern fit
The true pattern is hash map + doubly linked list. It is grouped here because interviewers often test whether you can manage pointers and ordering invariants cleanly.
Key observation
The list stores recency order, while the hash map gives O(1) access to the node that must be moved.
Target complexity
O(1) / O(capacity)
How to break down the solution cleanly
The true pattern is hash map + doubly linked list. It is grouped here because interviewers often test whether you can manage pointers and ordering invariants cleanly.
The list stores recency order, while the hash map gives O(1) access to the node that must be moved.
Write down what each pointer means before you move them.
Use the current comparison to prove which side can be safely discarded.
Reference implementation
Python# Generic pattern template
# Opposite-direction pointers on a sorted array
left, right = 0, len(nums) - 1
while left < right:
if good(nums[left], nums[right]):
return answer
if should_move_left(nums[left], nums[right]):
left += 1
else:
right -= 1
# Fast/slow pointers
slow = 0
for fast in range(len(nums)):
if keep(nums[fast]):
nums[slow] = nums[fast]
slow += 1
Common pitfalls
Using a normal queue that cannot delete arbitrary nodes in O(1).
Forgetting to update both prev and next pointers on remove/insert.
Common follow-ups
Why is a doubly linked list necessary?
How would LFU differ from LRU?
Continue with related problems
Build repeatable depth inside the Two Pointers cluster before moving on.