← Questions

LRU cache where each item counts by its quantity

0
SpaceXAICodingLast asked Feb 2026

A coding interview question asked in SpaceXAI's technical phone screen, last asked Feb 2026. It tests caching, hash maps and linked lists.

Implement a variant of the LRU cache in which capacity limits the total quantity of the stored items, not their number. Each item carries a positive integer quantity; an item of quantity 3 uses 3 units. Recency and eviction order work as in a normal LRU cache.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • WeightedLRUCache(capacity: int)
  • get(key: int) -> int — the value, marking the key most recently used, or -1.
  • put(key: int, value: int, quantity: int) -> None — inserts or overwrites (value and quantity) and marks the key most recently used; then, while the total quantity exceeds capacity, evicts the least recently used item.

Example

c = WeightedLRUCache(5)
c.put(1, 10, 2)        # {1}, total 2
c.put(2, 20, 2)        # {1, 2}, total 4
c.get(1)    ->  10     # key 2 is now least recent
c.put(3, 30, 3)        # total would be 7: evict 2 -> {1, 3}, total 5
c.get(2)    ->  -1
c.get(1)    ->  10

c = WeightedLRUCache(5)
c.put(1, 10, 2); c.put(2, 20, 2)
c.put(1, 11, 4)        # update: total 6 > 5, evict 2
c.get(2)    ->  -1
c.get(1)    ->  11

Constraints

  • 1 <= capacity <= 10^9; 1 <= quantity <= capacity; up to 2 * 10^5 calls.
  • get and put in average O(1); eviction is amortized O(1) because each item is evicted at most once.

Clarifying questions

  • Can a single item's quantity exceed the capacity? (Here no; if it could, should it be rejected or evict everything?)
  • On updating a key, does the new quantity replace the old one?
  • Can the item just inserted ever be evicted by its own put?
  • Does get count as a use for recency?

What a strong answer covers

  • A hash map from key to node plus a doubly linked list in recency order (or OrderedDict), and a running total of quantity.
  • Update path: subtract the old quantity before adding the new one, then move to the front.
  • An eviction loop from the tail until the total fits, with the amortized argument.
  • Edge cases: an update that shrinks or grows the item, an item equal to the whole capacity, repeated puts of the same key.
  • Tests that mirror the example and an update-triggered eviction.

Follow-ups

  • Allow items larger than the capacity: reject them without evicting anything.
  • Add peek that doesn't change recency.
  • Make it thread-safe.

Where it's asked

What it tests

caching · hash maps · linked lists

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding