Parcel-delivery app~20 min2s · 256 MBtarget O(q log n) time, O(1) spacebinary-search
A warehouse receives shipments of a product, one after another. After each shipment, the system records the total number of units received so far. The totals never go down, and they stay the same when a shipment is empty.
Customers place back-orders for a number of units. For each back-order, the warehouse wants to know the first shipment after which enough units had arrived.
Write first_covering_shipment(totals, orders).
totals[i] is the total number of units received after shipment i. The list never goes down.orders[j], find the smallest i with totals[i] >= orders[j].-1.Input: totals = [0, 0, 40, 40, 75, 120, 120, 200], orders = [30, 40, 41, 120, 200, 201]
Output: [2, 2, 4, 5, 7, -1]Each answer is the first position whose total reaches the order size.
| Order size | First shipment that covers it | Units received by then |
|---|---|---|
| 30 | 2 | 40 |
| 40 | 2 | 40 |
| 41 | 4 | 75 |
| 120 | 5 | 120 |
| 200 | 7 | 200 |
| 201 | none | none |
Shipments 0 and 1 brought nothing, and shipment 2 brought 40 units. An order of 40 is covered at shipment 2, the first one that reaches it, and not at shipment 3, which has the same total. No shipment reaches 201.
Input: totals = [5], orders = [5, 6]
Output: [0, -1]The only total is 5. It covers an order of 5 at shipment 0, and nothing covers 6.
Input: totals = [10, 10, 10], orders = [10]
Output: [0]Three shipments have the same total. The answer is the first one, shipment 0.
1 ≤ totals.length ≤ 100,000; 0 ≤ totals[i] ≤ 1,000,000,000, never going down1 ≤ orders.length ≤ 100,000; 1 ≤ orders[j] ≤ 1,000,000,000Scanning the totals from the start for each order costs up to n × q = 10^10 steps. The totals are sorted, so the first position that reaches a value can be found by halving the range: about 17 steps for 100,000 totals.