Weighted Eviction Cache

Asked at NetflixPhone screen

Reported by the problem's creator, not verified

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.

Examples

  1. Example 1

    Input: 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]

    Explanation: 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.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.