Online store~15 min2s · 256 MBtarget O(n) time, O(1) spaceprefix-sums
You work on the warehouse system of an online store. A long shelf has numbered slots in a row, and each slot holds a load, a whole number of weight units. The shelf rests on one support that can sit directly under any slot.
A load pulls the shelf down with a force that grows with its distance from the support. Your team lead asks: "Under which slot should the support go so that the shelf does not tip?"
Write balance_slot(loads).
loads[i] is the weight in slot i. The slots are numbered from 0.p, the left torque is the sum of loads[i] × (p - i) for every i < p. The right torque is the sum of loads[i] × (i - p) for every i > p. The load in slot p itself has distance 0.p where the shelf balances, or -1 when there is none.Input: loads = [4, 0, 2, 2, 2, 6]
Output: 3| Support under slot | Left torque | Right torque | Balanced |
|---|---|---|---|
| 0 | 0 | 48 | no |
| 1 | 4 | 36 | no |
| 2 | 8 | 24 | no |
| 3 | 14 | 14 | yes |
Slots 4 and 5 are not needed, because the answer is the smallest slot. The torques there are 22 and 6, then 32 and 0.
Input: loads = [5, 1, 2]
Output: -1The left torque starts at 0 and only grows. The right torque only falls. They are 0 and 5, then 5 and 2, then 11 and 0, and they never meet.
Input: loads = [0, 0, 0]
Output: 0Every slot balances an empty shelf, and the answer is the smallest.
1 ≤ loads.length ≤ 200,000 (slots)0 ≤ loads[i] ≤ 10,000Computing both torques for one support reads every other slot, about 200,000 steps. For 200,000 supports that is 40 billion steps.
The torques of neighbouring supports are linked. If you keep running totals of the weight and of the weight times its slot number, both torques follow in a few steps.
A torque can reach 10,000 × 200,000 × 200,000 = 400 trillion, so it needs 64 bits.