Implement a Weighted Eviction Cache
Company: Netflix
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency with data structures and algorithmic design for resource-constrained caching, specifically weight-aware eviction policies combined with LRU tie-breaking, and the ability to reason about efficiency and stateful operation under capacity limits.
Constraints
- 0 <= max_weight <= 10^9
- 0 <= key <= 10^9
- 0 <= value <= 10^9
- 1 <= weight <= 10^9 for every put operation
- 1 <= len(operations) <= 2 * 10^5
- operations[i][0] is either 1 or 2
Examples
Input: (10, [[1, 1, 100, 4], [1, 2, 200, 6], [2, 1], [1, 3, 300, 6], [2, 2], [2, 3]])
Expected Output: [100, -1, 300]
Explanation: After inserting key 3, total weight becomes 16. The largest weight is 6, shared by keys 2 and 3. Key 2 is less recent, so it is evicted. The get results are 100, -1, and 300.
Input: (8, [[1, 1, 10, 4], [1, 2, 20, 4], [2, 1], [1, 3, 30, 4], [2, 2], [2, 1], [2, 3]])
Expected Output: [10, -1, 10, 30]
Explanation: The get on key 1 makes it most recently used among weight-4 entries. When key 3 is inserted, the cache must evict one weight-4 entry, so key 2 is removed as the least recently used.
Input: (7, [[1, 1, 10, 3], [1, 2, 20, 3], [1, 1, 15, 5], [2, 1], [2, 2]])
Expected Output: [-1, 20]
Explanation: Updating key 1 replaces its old weight 3 with weight 5. The total becomes 8, so the cache evicts the largest-weight entry, which is key 1 itself. Key 2 remains.
Input: (5, [[1, 1, 10, 7], [2, 1], [1, 2, 20, 3], [1, 3, 30, 3], [2, 2], [2, 3]])
Expected Output: [-1, -1, 30]
Explanation: Key 1 has weight 7, which is larger than the capacity, so it is immediately evicted. Later, inserting key 3 causes total weight 6, so between keys 2 and 3 with equal weight 3, key 2 is evicted as the least recently used.
Input: (0, [[1, 5, 50, 1], [2, 5], [1, 6, 60, 2], [2, 6]])
Expected Output: [-1, -1]
Explanation: The cache has zero total capacity, so every inserted entry is immediately evicted.
Hints
- Recency only matters when weights tie, so consider maintaining a separate LRU order for each weight.
- You need to find the current largest weight quickly; a max-heap with lazy deletion works well with per-weight buckets.