Parcel-delivery app~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1769greedy
You work on a parcel-delivery app. A sorting belt has n slots in a row. Each slot holds one box or is empty.
A worker can move one box one slot to the left or to the right, and that is one move. Your team lead asks: "For every slot, how many moves does it take to bring all the boxes to that slot? We want a number for each slot, to choose a collection point."
Write moves_to_each_slot(slots).
slots is a string of 0 and 1. A 1 is a slot with a box, and a 0 is an empty slot.n numbers. Number i is the total moves to bring every box to slot i, each box moved on its own.Input: slots = "0101101"
Output: [14, 10, 8, 6, 6, 8, 10]A box at slot j costs |i - j| moves to reach slot i. Split each total into the boxes on the left and the boxes on the right. One pass from the left and one pass from the right each carry two numbers.
| Slot | Box? | Moves for boxes on the left | Moves for boxes on the right | Total |
|---|---|---|---|---|
| 0 | 0 | 0 | 14 | 14 |
| 1 | 1 | 0 | 10 | 10 |
| 2 | 0 | 1 | 7 | 8 |
| 3 | 1 | 2 | 4 | 6 |
| 4 | 1 | 4 | 2 | 6 |
| 5 | 0 | 7 | 1 | 8 |
| 6 | 1 | 10 | 0 | 10 |
Each total is the left part plus the right part. For slot 3 the boxes at slots 1, 3, 4 and 6 cost 2, 0, 1 and 3 moves, which is 6.
Input: slots = "100"
Output: [0, 1, 2]The only box is at slot 0, so slot i costs i moves.
Input: slots = "000"
Output: [0, 0, 0]There are no boxes, so every slot costs 0.
1 ≤ len(slots) ≤ 100,000slots holds only 0 and 1There can be 100,000 slots. For each slot, adding the distance to every box costs n steps, so the whole answer costs n^2, which is 10 billion steps. Two passes cost 200,000 steps. A single value can reach about 5 billion, so use 64-bit numbers.