Design and implement an LRU (Least Recently Used) cache where the cache capacity is measured by total size, not by item count.
Each cached item has a variable size (positive integer). The cache has a maximum capacity maxSize.
Implement the following operations:
get(key) -> value | null
key
exists, else return
null
.
put(key, value, size)
size
.
maxSize
, evict
one or more
least-recently-used items until
totalSize <= maxSize
.
size
is a positive integer.
size > maxSize
, define and document expected behavior (commonly: do not store the item at all).
O(1)
average time for
get
and
put
(excluding time spent evicting multiple items).
maxSize = 10
put(A, ..., size=6)
→ total=6
put(B, ..., size=5)
→ total would be 11, so evict LRU items until total<=10 (likely evict
A
if it is LRU)
Describe data structures and invariants you would maintain.