#146
Medium
Two Pointers

LRU Cache

Design an LRU cache with O(1) get and put.

DesignHash Table

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

1

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.

2

The list stores recency order, while the hash map gives O(1) access to the node that must be moved.

3

Write down what each pointer means before you move them.

4

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

warning

Using a normal queue that cannot delete arbitrary nodes in O(1).

warning

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.

view_weekBack to the pattern page
LeetCode 146. LRU Cache Guide | Interview AiBox