Design a LRU Cache
Quick Overview
Implement a Least Recently Used cache with O(1) get and put operations. Requires combining a hash map with a doubly linked list. A Google classic.
0
Implement a Least Recently Used cache with O(1) get and put operations. Requires combining a hash map with a doubly linked list. A Google classic.
LRU Cache is a Google phone screen classic that tests whether you can combine two data structures to hit O(1) for both get and put. The interviewer watches for correct pointer handling in the doubly linked list, clean eviction logic and code that is ready to run.
What the Interviewer Expects
- Pair a hash map (key to node) with a doubly linked list ordered by recency
- Move a node to the front on every get and put
- Evict the tail node and delete its key from the map when capacity is exceeded
- Use sentinel head and tail nodes to remove null checks
- State O(1) time per operation and O(capacity) space
- Handle updating an existing key and capacity edge cases
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you make the cache thread-safe without a global lock becoming a bottleneck?
- How would you implement LFU instead of LRU?
- How would you add per-entry time-to-live expiration?
- Could you use OrderedDict, and what would an interviewer think of that?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
This problem requires implementing an LRU (Least Recently Used) cache, which means we need to efficiently track the order of item usage. The key operations are get and put, which must both run in ...
Approach
- Data Structures: Use a hash map to store keys and their corresponding nodes in the doubly linked list. Each node will hold the key and value. The doubly linked list allows for efficient inserti...