Netflix questions

Weighted Eviction Cache

NetflixPhone screenMedium

Design a cache that stores integer entries under a total weight limit. Every entry has a key, a value and a weight of at least 1, and the total weight of all stored entries may never exceed the capacity. Whenever the total weight is above the capacity, the cache evicts the entry with the largest weight, breaking ties by the smaller key, and repeats until the total fits. Reading an entry does not change which entry is evicted next.

Each test drives one WeightedCache instance through a sequence of calls and checks every return value.

Part 1: Evict the heaviest

Implement a weighted cache with a fixed capacity.

  • put(key, value, weight): if weight is greater than capacity, do nothing at all, even when key already exists. Otherwise store the entry, replacing any earlier entry under key together with its weight, then evict while the total weight of all entries exceeds capacity: each eviction removes the entry with the largest weight, breaking ties by the smaller key. The new entry can itself be evicted. Returns nothing.
  • get(key): returns the stored value, or -1 if key is not stored.

Reading an entry never changes which entry is evicted next.

  1. Example 1
    init
    [10]
    operations
    [["put",[1,100,4]],["put",[2,200,5]],["get",[1]],["get",[2]],["put",[3,300,3]],["get",[1]],["get",[2]],["get",[3]],["get",[9]]]
    Output
    [null,null,100,200,null,100,-1,300,-1]

    Why: Entries 1 (weight 4) and 2 (weight 5) fit in 10. Adding 3 (weight 3) makes the total 12, so the heaviest entry, key 2, is evicted and the total drops to 7.

Constraints

  • 1 <= len(operations) <= 10^4
  • 1 <= capacity <= 10^9
  • 1 <= weight <= 10^9
  • 0 <= key <= 10^9
  • 0 <= value <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Weighted Eviction Cache: Netflix interview question | LoopCoach