Implement an O(1) LRU Cache
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Implement an LRU cache whose get and put operations both run in O(1) time. Combine a hash map with a doubly linked list, then reason about eviction, recency updates, and extensions such as expiry or sharding.
Read the full Microsoft Software Engineer interview experience this question came from
Constraints
- 1 <= capacity <= 20.
- 0 <= operations.length <= 40, and every operation contains exactly three integers.
- Operation kinds are 0 for put and 1 for get; keys and values are between -1,000,000,000 and 1,000,000,000.
Examples
Input: (2, [[0, 1, 10], [0, 2, 20], [1, 1, 0], [0, 3, 30], [1, 2, 0], [1, 3, 0], [1, 1, 0]])
Expected Output: [10, -1, 30, 10]
Input: (2, [[0, 1, 1], [0, 2, 2], [0, 1, 10], [0, 3, 3], [1, 2, 0], [1, 1, 0], [1, 3, 0]])
Expected Output: [-1, 10, 3]
Hints
- Use a hash map for lookup and an ordering structure that can move or remove a known node in constant time.
- Treat updating an existing key as both a value change and a recency change.