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]