Weighted LRU Cache: Capacity Counted by Item Quantity
xAISoftware Engineer · OnsiteLast updated
This question evaluates understanding of cache design and LRU eviction semantics with weighted resource accounting, plus data-structure and amortized-complexity reasoning needed to support O(1) average-time operations.
Design a variant of the classic least-recently-used (LRU) cache. In the classic version, the capacity limits the number of items stored. In this variant, every item carries a positive integer quantity, and the capacity limits the total quantity across all stored items — an item with quantity 3 consumes 3 units of capacity, not 1. All other behavior (recency tracking, eviction order) is identical to a standard LRU cache.
Implement the class WeightedLRUCache:
WeightedLRUCache(int capacity)— initializes the cache with a positive integercapacity, the maximum total quantity the cache may hold at any time.int get(int key)— ifkeyexists in the cache, returns its value and marks the key as the most recently used; otherwise returns-1.void put(int key, int value, int quantity)— inserts or updates an entry:
- If
keyalready exists, overwrite its value and quantity, and mark it as the most recently used. - Otherwise, insert
keyas the most recently used entry. - Afterwards, while the sum of quantities of all stored items exceeds
capacity, evict the least recently used item.
An evicted key is removed entirely; a later get on it returns -1 (and a later put re-inserts it as a fresh entry).
Example
Input:
["WeightedLRUCache", "put", "put", "get", "put", "get", "get"]
[[5], [1, 10, 2], [2, 20, 2], [1], [3, 30, 3], [2], [1]]
Output:
[null, null, null, 10, null, -1, 10]
Explanation (capacity = 5):
put(1, 10, 2)— cache holds {1}, total quantity 2.put(2, 20, 2)— cache holds {1, 2}, total quantity 4.get(1)returns10and makes key 1 the most recently used; key 2 is now the least recently used.put(3, 30, 3)— total quantity would become 7 > 5, so the least recently used key 2 is evicted; cache holds {1, 3}, total quantity 5.get(2)returns-1(evicted).get(1)returns10.
Constraints
1 <= capacity <= 10^91 <= quantity <= capacityfor everyputcall0 <= key, value <= 10^9- At most
2 * 10^5calls will be made togetandputcombined.
Performance requirement
Both get and put must run in average O(1) time. The eviction loop inside put is amortized O(1): every stored item is evicted at most once, so total eviction work is bounded by the total number of insertions.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.