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.
Input: (2, [[2, 2, 1], [2, 2, 2], [1, 2, 0], [2, 1, 1], [2, 4, 1], [1, 2, 0], [1, 1, 0], [1, 4, 0]])
Expected Output: [2, -1, 1, 1]
Explanation: Updating key 2 changes its value to 2 and does not increase cache size. After inserting key 1, key 2 becomes least recent, so inserting key 4 evicts key 2.
Input: (3, [])
Expected Output: []
Explanation: No operations means there are no `get` results to return.
Input: (2, [[2, -1, -10], [2, -2, -20], [1, -1, 0], [2, -3, -30], [1, -2, 0], [1, -1, 0], [1, -3, 0]])
Expected Output: [-10, -1, -10, -30]
Explanation: Negative keys and values are valid. Accessing key -1 makes it most recent, so key -2 is evicted when key -3 is inserted.
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).