1 GPT-6.1 Sol OpenAI
from heapq import heapify, heappop
def allocate(lots, orders):
# Validate every input before allocating stock.
remaining = {}
for lot in lots:
if lot["qty"] < 0:
raise ValueError("Negative lot quantity")
if lot["id"] in remaining:
raise ValueError("Duplicate lot id")
remaining[lot["id"]] = lot["qty"]
seen_orders = set()
for order in orders:
if order["qty"] < 0:
raise ValueError("Negative order quantity")
if order["id"] in seen_orders:
raise ValueError("Duplicate order id")
seen_orders.a...
Show Full Answer ▼
from heapq import heapify, heappop
def allocate(lots, orders):
# Validate every input before allocating stock.
remaining = {}
for lot in lots:
if lot["qty"] < 0:
raise ValueError("Negative lot quantity")
if lot["id"] in remaining:
raise ValueError("Duplicate lot id")
remaining[lot["id"]] = lot["qty"]
seen_orders = set()
for order in orders:
if order["qty"] < 0:
raise ValueError("Negative order quantity")
if order["id"] in seen_orders:
raise ValueError("Duplicate order id")
seen_orders.add(order["id"])
heap = [(lot["expires"], lot["id"])
for lot in lots if lot["qty"] > 0]
heapify(heap)
usable_total = sum(remaining.values())
fills = {}
short = {}
# Python's stable sort preserves input order for equal days.
for order in sorted(orders, key=lambda order: order["day"]):
day = order["day"]
order_id = order["id"]
need = order["qty"]
fills[order_id] = []
# Expired stock stays in remaining but cannot be allocated.
while heap and heap[0][0] < day:
_, lot_id = heappop(heap)
usable_total -= remaining[lot_id]
if order.get("all_or_nothing", False) and need > usable_total:
short[order_id] = need
continue
while need > 0 and heap:
_, lot_id = heap[0]
taken = min(need, remaining[lot_id])
fills[order_id].append((lot_id, taken))
remaining[lot_id] -= taken
usable_total -= taken
need -= taken
if remaining[lot_id] == 0:
heappop(heap)
if need > 0:
short[order_id] = need
return {"fills": fills, "short": short, "remaining": remaining}
Validation completes before any allocation. Stable day sorting preserves the original order of same-day orders. The heap orders positive-stock lots by expiration and then lot ID. Because orders are processed chronologically, expired lots can be permanently removed from the heap without changing their final stock.
usable_total tracks all stock currently eligible for shipment, allowing an all-or-nothing order to be rejected without consuming anything. Normal orders consume heap-front stock until filled or exhausted. Zero-quantity orders receive empty fills and no shortage.
Let L be the number of lots, M the number of orders, and K the number of allocation tuples returned. Each lot is removed from the heap at most once. Time complexity is O(L log(L + 1) + M log(M + 1) + K); space complexity, including the output, is O(L + M + K).
A correct, efficient heap-based FEFO allocator. Reading through T1 to T6 gives the expected result every time: stable day sort, inclusive expiry, (expires, id) heap ordering, all_or_nothing checked against usable stock only, and validation that finishes before any allocation. The return shape is exact, the code is 58 lines, and the 129-word explanation gives a correct complexity bound. Flaws are minor.
Score by criterion
Correctness
Passes T1 to T6 by reading. The stable sort keeps same-day orders in input order. The expiry check pops lots only while expires < day, so expiry is inclusive. The heap orders lots by (expires, id). usable_total subtracts expired stock before the all_or_nothing check (T3 gives M [] and N [(Q,3)]). Zero-quantity orders get an empty fill and no short entry. A skipped all_or_nothing order consumes nothing. No logic errors found.
Completeness
Returns exactly fills, short and remaining. Every order id appears in fills, short holds only positive shortfalls, and remaining covers every lot, including expired lots. Negative quantities and duplicate ids for both lots and orders raise ValueError before allocation. Malformed inputs such as missing keys are not handled, but the task did not require it.
Code Quality
Clean and idiomatic. The heap plus a running usable_total avoids rescanning lots and avoids any per-unit loops, and the comments are concise. A minor quirk is that the stock dict is named remaining and also serves as the returned map, which works but couples the two roles.
Practical Value
Efficient and ready for real use. Its time cost is O(L log L + M log M + K), and the explanation clearly covers the design choices and edge cases such as zero-quantity orders and expired lots. It would be directly usable in a small warehouse tool.
Instruction Following
Uses only the standard library (heapq). The code is 58 lines, well under 150, and the explanation is 129 words, under 200. The complexity statement O(L log L + M log M + K) is correct and better than the reference bound.
The solution satisfies all requirements and passes T1–T6 by inspection. It correctly combines stable chronological order processing, heap-based FEFO allocation, and an accurate usable-stock total for all-or-nothing decisions. Validation, output structure, complexity analysis, and the stated length limits are all handled correctly.
Score by criterion
Correctness
Passes T1–T6 by inspection. Stable sorting preserves same-day order; heap ordering implements expiration and string-ID priority; expiry is inclusive. The usable-stock total excludes expired stock before each allocation, and rejected all-or-nothing orders consume nothing. Partial fills and zero-quantity orders behave correctly.
Completeness
Returns exactly fills, short, and remaining, with every order represented in fills, only positive shortages recorded, and every lot retained in remaining. Negative quantities and duplicate IDs are validated across both inputs before any allocation occurs.
Code Quality
The implementation is readable, self-contained, and efficient. Clear variable names and focused comments explain the heap and usable-stock invariant. Each lot is removed from the heap at most once, with no unnecessary repeated scans or per-unit processing.
Practical Value
Ready to use for the specified inputs without modifying caller-owned dictionaries. It handles empty inputs, exhausted stock, expired stock, zero quantities, and skipped all-or-nothing orders while preserving an accurate final inventory. The explanation gives correct output-sensitive time and space bounds.
Instruction Following
Provides the requested Python 3 function using only the standard library. The measured 58 code lines and 129 explanation words are within both limits, and the explanation explicitly states the correct time complexity.
The solution is exceptionally well-crafted, correct, and efficient. It uses a min-heap along with a running total of usable inventory to achieve optimal time complexity, accurately handles tie-breaking and stable sorting for same-day orders, and strictly adheres to all constraints and formatting specifications.
Score by criterion
Correctness
All test cases (T1-T6) pass cleanly. Usable stock is properly identified (expires >= day), tie-breaking by lot ID is respected via heap ordering, and the all-or-nothing check accurately checks against currently usable stock on that day.
Completeness
The function validates all negative quantities and duplicate IDs before any allocations occur, correctly returns the exact dictionary structure required, and properly omits fully fulfilled orders from the 'short' mapping.
Code Quality
The code is idiomatic, clean, readable, and highly efficient. Maintaining `usable_total` dynamically alongside heap eviction avoids redundant scanning over lots.
Practical Value
The implementation handles practical warehouse edge cases seamlessly (zero-quantity orders, lots expiring between orders, all-or-nothing thresholding) and is production-ready.
Instruction Following
Strictly adhered to all line count limits (58 lines <= 150), explanation word count limits (129 words <= 200), standard library constraints, and included a clear time complexity analysis.