Design LFU cache with distributed extension
Company: Amazon
Role: Applied Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates understanding of cache design and frequency-based eviction policies, efficient data structures that support O(1) operations, and techniques for approximate frequency estimation and summarization in distributed streaming environments.
Constraints
- 0 <= capacity
- Keys and values fit in 32-bit signed integers.
- Each operation is either ["put", key, value] or ["get", key].
- On eviction, remove the least frequently used key; break ties by least recently used.
- If capacity == 0, every put is a no-op and every get returns -1.
Examples
Input: (2, [["put", 1, 1], ["put", 2, 2], ["get", 1], ["put", 3, 3], ["get", 2], ["get", 3], ["put", 4, 4], ["get", 1], ["get", 3], ["get", 4]])
Expected Output: [None, None, 1, None, -1, 3, None, -1, 3, 4]
Explanation: Classic LeetCode trace. After get(1), key 1 has freq 2 and key 2 has freq 1, so put(3) evicts key 2. Later both keys 1 and 3 have freq 2; key 1 was accessed less recently, so put(4) evicts key 1.
Input: (0, [["put", 0, 0], ["get", 0]])
Expected Output: [None, -1]
Explanation: Zero capacity: the put stores nothing and the get returns -1.
Hints
- Maintain three maps: key -> value, key -> frequency, and frequency -> ordered collection of keys at that frequency (insertion-ordered so the front is the least recently used).
- Track a running min_freq. When you bump a key's frequency, remove it from its old frequency bucket; if that bucket was the min_freq bucket and becomes empty, increment min_freq.
- On insertion into a full cache, evict the front (oldest) key of the min_freq bucket, then set min_freq back to 1 for the newly inserted key.
- An OrderedDict (or a doubly-linked list per frequency) gives O(1) insertion, removal, and oldest-key eviction, which is what keeps both operations O(1).