call(back)
Algorithms & Data StructuresmediumSign in to star problems

FIFO Order Allocator

Allocate stock to orders first in, first out: each order consumes the oldest stock first, and the result says which lots it drew from and how much from each.

allocator.receive(lotId, quantity, receivedAt)   // add stock
allocator.allocate(orderId, quantity)            // -> [{ lotId, quantity }, ...] or null
allocator.available()                            // -> total units in stock
allocator.lots()                                 // -> remaining lots in consumption order

Rules

  • Orders draw from the oldest lot first (smallest receivedAt); lots with the same receivedAt are consumed in the order they were received.
  • A lot may be consumed partially; the remainder stays at the front. Exhausted lots disappear from lots().
  • Allocation is all-or-nothing: if stock can't cover the whole order, return null and change nothing.
  • allocate returns the lots drawn from, in consumption order, with the quantity taken from each. A quantity of 0 allocates nothing and returns [].
  • Lots can arrive out of receivedAt order.

Hints

Hint 1

Keep the lots as an array sorted by (receivedAt, arrival sequence) — a stamp you assign on receive() makes the tie-break explicit rather than relying on sort stability.

Hint 2

Check available() >= quantity before touching anything, so all-or-nothing falls out naturally; then walk from the front taking min(lot.quantity, remaining) until remaining hits zero.

Asked at