#146

LRU Cache

Medium HashMap + doubly linked list

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design a fixed-capacity cache with get and put in O(1). When full, put evicts the least recently used key.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: a cache that evicts the least recently used key, with O(1) get and put.

Why this works: the HashMap finds nodes; the doubly linked list keeps usage order (most recent at the front) and removes any node in O(1).

Example: capacity 2: put 1, put 2, get 1, put 3

order after get 1: [1, 2]put 3 evicts the tail 2 → [3, 1]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to remove the evicted key from the HashMap, so the map keeps growing and returns stale nodes.

Solve on LeetCode ↗
Complexity
  • Time: O(1) per operation.
  • Space: O(capacity).
Topic: Linked List
🎬 Episodes 40–45: video coming soon