Build a least-recently-used cache
Company: Anthropic
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's competence in designing and implementing efficient in-memory cache mechanisms, focusing on data structures, eviction policies, and algorithmic time-space complexity.
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) == len(arguments) <= 2 * 10^5
- operations[i] is either "get" or "put"
- For "get", arguments[i] has length 1; for "put", arguments[i] has length 2
- -10^9 <= key, value <= 10^9
- Target average time per operation: O(1)
Examples
Input: (2, ["put", "put", "get", "put", "get", "put", "get", "get", "get"], [(1, 1), (2, 2), (1,), (3, 3), (2,), (4, 4), (1,), (3,), (4,)])
Expected Output: [None, None, 1, None, -1, None, -1, 3, 4]
Explanation: After inserting 1 and 2, get(1) makes key 1 most recently used. put(3,3) evicts key 2. Later put(4,4) evicts key 1.
Input: (2, ["put", "put", "put", "get", "put", "get", "get"], [(2, 1), (2, 2), (1, 1), (2,), (4, 1), (2,), (1,)])
Expected Output: [None, None, None, 2, None, 2, -1]
Explanation: Updating an existing key should change its value and move it to most recently used. Key 1 is later evicted when key 4 is inserted.
Input: (1, ["put", "put", "get", "get", "put", "get"], [(1, 10), (2, 20), (1,), (2,), (2, 30), (2,)])
Expected Output: [None, None, -1, 20, None, 30]
Explanation: With capacity 1, every new key evicts the previous one. Updating key 2 changes its stored value to 30.
Input: (2, ["get", "put", "put", "get", "put", "get", "get"], [(5,), (-1, -10), (5, 50), (-1,), (6, 60), (5,), (6,)])
Expected Output: [-1, None, None, -10, None, -1, 60]
Explanation: The first get misses. Accessing key -1 makes it most recently used, so inserting key 6 evicts key 5.
Input: (3, [], [])
Expected Output: []
Explanation: No operations means no outputs.
Hints
- You need one structure for fast lookup by key and another for maintaining usage order.
- A doubly linked list with dummy head and tail nodes lets you remove and reinsert nodes in O(1).