Implement a Least-Recently-Used Cache
Company: Anthropic
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to design and implement an efficient in-memory cache with eviction behavior, testing understanding of data structure selection, state management, and time/space complexity under capacity constraints.
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) <= 2 * 10^5
- Each operation has exactly 3 integers
- operation[0] is either 1 (get) or 2 (put)
- -10^9 <= key, value <= 10^9
Examples
Input: (2, [[2, 1, 1], [2, 2, 2], [1, 1, 0], [2, 3, 3], [1, 2, 0], [2, 4, 4], [1, 1, 0], [1, 3, 0], [1, 4, 0]])
Expected Output: [1, -1, -1, 3, 4]
Explanation: After `get(1)`, key 1 becomes most recent, so key 2 is evicted when key 3 is inserted. Later key 1 is evicted when key 4 is inserted.
Input: (1, [[2, 2, 1], [1, 2, 0], [2, 3, 2], [1, 2, 0], [1, 3, 0]])
Expected Output: [1, -1, 2]
Explanation: With capacity 1, inserting key 3 evicts key 2.
Hints
- A hash map can find a key in O(1), but by itself it cannot tell you which key is least recently used.
- Use a doubly linked list with dummy head and tail nodes so you can remove or move any cache entry in O(1).