Caching Library with Pluggable LRU, LFU and FIFO Eviction Policies
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a thread-safe caching library that supports pluggable eviction policies. The cache is created with a maximum `capacity` and an eviction `policy` string, which is one of `'LRU'`, `'LFU'` or `'FIFO'`.
When the cache is full and a new key needs to be inserted, the current eviction policy decides which existing entry to remove. LRU evicts the least recently accessed entry. LFU evicts the least frequently accessed entry, using least recent access as the tiebreaker. FIFO evicts the entry that was inserted earliest.
The eviction policy can be changed at any time. When it changes, all existing entries are retained, and only future evictions use the new policy. Accessing or updating an existing key counts as a use for both LRU recency tracking and LFU frequency tracking.
Implement the following methods:
- `get(key: int) -> int`: return the value associated with the key if it exists in the cache, otherwise return -1. Accessing a key updates its recency and frequency.
- `put(key: int, value: int)`: insert or update the key-value pair. If the cache is at capacity and the key is new, evict one entry according to the current eviction policy before inserting.
- `evict() -> int`: manually evict the next entry according to the current eviction policy. Return the evicted key, or -1 if the cache is empty.
- `changePolicy(policy: str)`: change the eviction policy to `'LRU'`, `'LFU'` or `'FIFO'`. All existing entries are retained.
- `size() -> int`: return the current number of entries in the cache.
Example 1 (capacity 2, LRU):
```text
Input:
["CacheLibrary", "put", "put", "put", "get", "put", "get", "get", "evict", "size"]
[[2, "LRU"], [1, 10], [2, 20], [3, 30], [3], [4, 40], [2], [3], [], []]
Output: [null, null, null, null, 30, null, -1, 30, 4, 1]
Explanation:
cache = CacheLibrary(2, 'LRU') # capacity = 2, policy = LRU
cache.put(1, 10) # cache: {1=10}
cache.put(2, 20) # cache: {1=10, 2=20}
cache.put(3, 30) # evicts key 1 (LRU), cache: {2=20, 3=30}
cache.get(3) # -> 30 (key 3 exists, now most recently used)
cache.put(4, 40) # evicts key 2 (LRU), cache: {3=30, 4=40}
cache.get(2) # -> -1 (key 2 was evicted)
cache.get(3) # -> 30 (key 3 still in cache)
cache.evict() # -> 4 (key 4 is LRU, evicted), cache: {3=30}
cache.size() # -> 1 (one entry remains)
```
Example 2 (capacity 2, LFU, then FIFO):
```text
Input:
["CacheLibrary", "put", "put", "put", "get", "get", "changePolicy", "put", "get", "size"]
[[2, "LFU"], [1, 100], [2, 200], [1, 150], [1], [2], ["FIFO"], [3, 300], [2], []]
Output: [null, null, null, null, 150, 200, null, null, 200, 2]
Explanation:
cache = CacheLibrary(2, 'LFU') # capacity = 2, policy = LFU
cache.put(1, 100) # cache: {1=100}, freq(1)=1
cache.put(2, 200) # cache: {1=100, 2=200}, freq(2)=1
cache.put(1, 150) # update key 1, cache: {1=150, 2=200}, freq(1)=2
cache.get(1) # -> 150 (freq(1) now 3)
cache.get(2) # -> 200 (freq(2) now 2)
cache.changePolicy('FIFO') # switch to FIFO, entries retained
cache.put(3, 300) # FIFO evicts key 1 (inserted first), cache: {2=200, 3=300}
cache.get(2) # -> 200 (key 2 still in cache)
cache.size() # -> 2 (two entries in cache)
```
```hint Metadata per entry
List what each of the three policies needs to know about an entry to pick a victim. Then ask what a policy switch costs if every entry always carries all of it.
```
```hint Locking pitfall
`put` can trigger an eviction, and `evict` is public too. Check what happens when one locked method calls another under a non-reentrant lock, and remember that `get` changes state.
```
### Constraints & Assumptions
- `1 <= capacity <= 3000`
- `0 <= key <= 10^4`
- `0 <= value <= 10^5`
- `policy` is one of `'LRU'`, `'LFU'`, `'FIFO'`
- At most `10^4` calls are made in total.
- Any method may be called from several threads at once.
### Clarifying Questions to Ask
- Does updating an existing key move it to the back of the FIFO order, or does FIFO only look at the first insertion?
- Does a `get` on a missing key change any policy state?
- Does the insertion itself count as the first use for LFU frequency?
- What should happen when `changePolicy` receives a name outside the three supported policies?
- Is a scan over all entries per eviction acceptable at this scale, or is faster eviction expected?
### What a Strong Answer Covers
- The metadata kept per entry, and how it stays valid across policy switches without any migration.
- A policy abstraction that lets a new eviction rule be added without changing the cache core.
- Exact eviction semantics for each policy, including the LFU tiebreak and FIFO behavior when a key is updated.
- Thread safety: which operations must be atomic, and how the internal eviction path avoids taking the lock twice.
- Time and space complexity per operation, and how eviction could be made faster than a full scan.
### Follow-up Questions
- How would you make eviction O(1) or O(log n) per call while keeping policy switches free?
- One global lock limits throughput. How would you scale the cache across many threads, and what eviction accuracy would you give up?
- How would you add per-entry TTL expiration alongside the eviction policy?
- Under LFU, keys that were popular long ago can stay forever. How would you age the frequencies?
Overview: Design a thread-safe cache library whose eviction policy can switch between LRU, LFU and FIFO at runtime while keeping every entry. It tests how you store per-entry metadata, structure a pluggable policy, lock reads that change state, and reason about the cost of eviction.