Design an LRU cache with get, put and size in O(1) average time
Company: Miro
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a specialized cache that combines the properties of an LRU (least recently used) cache with a fixed capacity. The cache stores key-value pairs and tracks recency of access for both `get` and `put` operations.
When the cache reaches its capacity and a new key is inserted, it must evict the least recently used key to make room. Accessing a key (through `get`, or updating it through `put`) marks it as most recently used.
Both `get` and `put` must run in **average `O(1)` time**.
Implement the following methods:
- `SpecializedCache(capacity: int)`: create an empty cache that holds at most `capacity` key-value pairs.
- `get(key: int) -> int`: return the value associated with the key if it exists in the cache, otherwise return -1. Marks the key as most recently used.
- `put(key: int, value: int)`: insert or update the key-value pair. If the cache exceeds capacity after insertion, evict the least recently used key. Marks the key as most recently used.
- `size() -> int`: return the current number of key-value pairs stored in the cache.
Example 1:
```text
Input:
["SpecializedCache", "put", "put", "get", "put", "get", "size", "put", "get", "get"]
[[2], [1, 10], [2, 20], [1], [3, 30], [2], [], [4, 40], [1], [3]]
Output: [null, null, null, 10, null, -1, 2, null, -1, 30]
Explanation:
cache = SpecializedCache(2) # capacity = 2
cache.put(1, 10) # cache: {1=10}
cache.put(2, 20) # cache: {1=10, 2=20}
cache.get(1) # -> 10 (key 1 is now most recently used)
cache.put(3, 30) # evicts key 2 (LRU), cache: {1=10, 3=30}
cache.get(2) # -> -1 (key 2 was evicted)
cache.size() # -> 2 (current entries)
cache.put(4, 40) # evicts key 1 (LRU), cache: {3=30, 4=40}
cache.get(1) # -> -1 (key 1 was evicted)
cache.get(3) # -> 30
```
Example 2:
```text
Input:
["SpecializedCache", "put", "put", "put", "get", "get", "size"]
[[1], [5, 50], [6, 60], [7, 70], [5], [7], []]
Output: [null, null, null, null, -1, 70, 1]
Explanation:
cache = SpecializedCache(1) # capacity = 1
cache.put(5, 50) # cache: {5=50}
cache.put(6, 60) # evicts key 5, cache: {6=60}
cache.put(7, 70) # evicts key 6, cache: {7=70}
cache.get(5) # -> -1 (key 5 was evicted)
cache.get(7) # -> 70 (key 7 most recently used)
cache.size() # -> 1
```
```hint Two structures
A hash map finds a key in O(1) but remembers nothing about order. Ask which structure lets you move an arbitrary entry to one end, or drop the entry at the other end, in O(1) once you hold a reference to it.
```
```hint Updates at full capacity
Trace `put` on a key that is already stored while the cache is full. The count does not change, so nothing should be evicted, yet the key still becomes the most recently used.
```
### Constraints & Assumptions
- `1 <= capacity <= 10⁴`
- `0 <= key, value <= 10⁹`
- At most `2 * 10⁵` calls will be made to `get` and `put`.
- Keys and values are non-negative, so -1 is never a stored value and can safely mean "missing".
### Clarifying Questions to Ask
- May I use the language's built-in ordered map (`OrderedDict` in Python, `LinkedHashMap` in Java), or should I build the doubly linked list myself?
- Will the cache be called from several threads at once, or is single-threaded use enough?
### What a Strong Answer Covers
- Pairing a hash map with a structure that keeps recency order, and why neither one alone gives `O(1)` for both operations.
- Correct recency updates on a `get` hit, a `put` update and a `put` insert, with a `get` miss leaving the order unchanged.
- Eviction only when a new key pushes the count over capacity, removing the least recently used entry from every structure that holds it.
- Time and space complexity, including why the bound is average and not worst case.
- Edge cases such as capacity 1, updating an existing key at full capacity, and a stored value of 0.
### Follow-up Questions
- How would you implement it without `OrderedDict`, using your own doubly linked list?
- How would you make the cache safe to use from multiple threads, given that `get` also changes state?
- How would you add a per-entry time-to-live so that expired entries are never returned?
- How would the design change for an LFU (least frequently used) eviction policy?
Overview: Design a fixed-capacity cache that evicts the least recently used key and supports get, put and size in average O(1) time. It tests whether you can pair a hash map with a doubly linked list and keep recency order correct across reads, updates and evictions.