LRU Cache
Design an LRU Cache with O(1) get and put operations. Think about: What data structures enable O(1) access and ordering? Hint: Combine a hash map with a doubly linked list. Example: LRUCache(2) put(1, 1), put(2, 2) get(1) → 1 put(3, 3) # evicts key 2 get(2) → -1
Design a cache that evicts the least recently used item when full. It's one of the few problems that tests both data structure intuition and clean API design. Interviewers love it because it reveals whether you can combine a hash map with a linked list to get O(1) operations. This pattern shows up constantly in systems design.
Examples
You write
LRUCache: get(key: int), put(key: int, value: int)
Example 1
- Input
- LRUCache(2), put(1,1), put(2,2), get(1) => 1, put(3,3), get(2) => -1, put(4,4), get(1) => -1, get(3) => 3, get(4) => 4
- returns
- [1, -1, -1, 3, 4]
Example 2
- Input
- LRUCache(1), put(1,1), get(1) => 1, put(2,2), get(1) => -1, get(2) => 2
- returns
- [1, -1, 2]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsDesign
I reach for it when
- The statement describes a class with methods, not one function.
- Each method needs to be fast, and the structure decides how fast.
Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.
All 27 Design problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.