Implement weighted-eviction cache
Company: Netflix
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates understanding and practical implementation of data structures and algorithms for a weighted cache, including weighted eviction policies, use of ordered maps, and time-space complexity analysis.
Constraints
- 0 <= len(operations) <= 200000
- 0 <= capacity <= 10^12
- Operations are arrays: ["put", key, value, weight] or ["get", key]
- Keys and values are 32-bit signed integers
- 1 <= weight <= 10^9 for put operations
- If weight > capacity, the put is ignored and the cache is unchanged
- On put of an existing key, first replace its value and weight, then apply eviction
- When evicting due to capacity overflow, evict exactly one key: the key with the largest weight; ties broken by smallest key
- Return "null" for every put operation; return the stored value or -1 for get
Hints
- Maintain key -> (value, weight, version) in a hash map for O(1) access.
- Use a max-priority structure to find the largest weight quickly; in Python, use a min-heap with negative weights.
- To break ties by smallest key, include the key as the second component of the heap tuple.
- Handle updates by storing a version/timestamp per key and marking old heap entries as stale.
- Subtract the old weight before adding the new weight on put; if overweight, evict the current maximum.