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.
Operations
Implement the following operations:
-
get(key) -> value | null
-
Return the value if
key
exists, else return
null
.
-
If the key exists, mark it as
most recently used
.
-
put(key, value, size)
-
Insert or update an item with the given
size
.
-
Mark the item as
most recently used
.
-
If inserting/updating causes total cached size to exceed
maxSize
, evict
one or more
least-recently-used items until
totalSize <= maxSize
.
Requirements / Clarifications
-
size
is a positive integer.
-
If
size > maxSize
, define and document expected behavior (commonly: do not store the item at all).
-
Updating an existing key may change its size; eviction may be needed.
-
Target time complexity:
O(1)
average time for
get
and
put
(excluding time spent evicting multiple items).
Example
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.