Design LRU cache with O(1) operations
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of data structures and algorithm design, specifically skills in implementing constant-time cache operations, eviction policies, update handling, and concurrency/thread-safety considerations.
Constraints
- 0 <= capacity <= 100000
- 0 <= len(operations) <= 200000
- -1000000000 <= key, value <= 1000000000
- Average time complexity for each get and put should be O(1)
Examples
Input: (2, [('put', 1, 1), ('put', 2, 2), ('get', 1), ('put', 3, 3), ('get', 2), ('put', 4, 4), ('get', 1), ('get', 3), ('get', 4)])
Expected Output: [None, None, 1, None, -1, None, -1, 3, 4]
Explanation: After get(1), key 1 becomes most recently used, so inserting key 3 evicts key 2. Later inserting key 4 evicts key 1.
Input: (2, [('put', 1, 1), ('put', 2, 2), ('put', 1, 10), ('put', 3, 3), ('get', 1), ('get', 2), ('get', 3)])
Expected Output: [None, None, None, None, 10, -1, 3]
Explanation: Updating key 1 changes its value to 10 and makes it most recently used. Then key 2 is the one evicted when key 3 is inserted.
Input: (0, [('put', 1, 1), ('get', 1), ('put', 2, 2), ('get', 2)])
Expected Output: [None, -1, None, -1]
Explanation: With capacity 0, the cache can never store anything, so every get returns -1.
Input: (1, [('put', -1, -10), ('get', -1), ('put', 2, 20), ('get', -1), ('get', 2)])
Expected Output: [None, -10, None, -1, 20]
Explanation: The cache can hold only one item. Inserting key 2 evicts key -1.
Input: (3, [])
Expected Output: []
Explanation: No operations means no results.
Hints
- A hash map can tell you in O(1) where a key currently lives in the cache.
- Use a doubly linked list with dummy head and tail nodes so you can remove the least recently used item and move accessed items to the front in O(1).