Implement an LRU Cache
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Implement an LRU cache with constant-time lookup, recency updates, and eviction, including existing-key updates, zero capacity, and concurrency pitfalls.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- 0 <= capacity <= 2^53 - 1.
- 0 <= operations.length <= 2^31 - 1.
- Each record is exactly [0, key] or [1, key, value].
- Keys and stored values are integers from -(2^53 - 1) to 2^53 - 1, inclusive.
- Target O(1) average time per get or put.
Examples
Input: (2, [[1, 10, 100], [1, 20, 200], [0, 10], [1, 30, 300], [0, 20], [0, 30], [0, 10]])
Expected Output: [100, -1, 300, 100]
Explanation: Getting key 10 makes it most recently used. Putting key 30 then evicts key 20.
Input: (2, [[1, 4, 40], [1, 5, 50], [1, 4, 41], [1, 6, 60], [0, 4], [0, 5], [0, 6]])
Expected Output: [41, -1, 60]
Explanation: Updating key 4 changes its value to 41 and makes it most recently used. Putting key 6 evicts key 5.
Hints
- Trace the keys from least to most recently used after a hit, a miss, and an update.