Implement an LRU cache
Company: Affirm
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to design and implement efficient cache eviction policies while managing time and space complexity guarantees for mutable key-value stores.
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) <= 2 * 10^5
- operations[i] is either [0, key] or [1, key, value]
- -10^9 <= key, value <= 10^9
- Both get and put must run in average O(1) time
Examples
Input: (2, [[1,1,1], [1,2,2], [0,1], [1,3,3], [0,2], [1,4,4], [0,1], [0,3], [0,4]])
Expected Output: [1, -1, -1, 3, 4]
Explanation: After get(1), key 1 becomes most recent. put(3,3) evicts key 2. Later put(4,4) evicts key 1. The get results are 1, -1, -1, 3, and 4.
Input: (2, [[1,1,1], [1,2,2], [1,1,10], [0,1], [1,3,3], [0,2], [0,1], [0,3]])
Expected Output: [10, -1, 10, 3]
Explanation: Updating key 1 changes its value to 10 and makes it most recent. When key 3 is inserted, key 2 is least recently used and is evicted.
Hints
- Use a hash map to find cache entries by key in O(1) average time.
- Use a doubly linked list to track recency: move accessed or updated nodes to the front, and evict from the back.