Parcel-delivery app~25 min2s · 256 MBtarget O(n) time, O(n) spaceprefix-sum-hashmap
You work on a parcel-delivery app. A truck drives a loop of hubs. At each hub it picks up parcels or drops them, so its load changes by a number: positive for a pick-up, negative for a drop-off.
A driver can start at any hub and serve some hubs in a row, going round the loop. The route may pass the last hub and continue at the first one. Your team lead asks: "How many such runs end with a net change equal to the budget?"
Write count_loop_runs(changes, budget).
changes[i] is the load change at hub i. The hubs form a loop: after hub n - 1 comes hub 0.n.changes.n covers all hubs, so it is one run whatever its start.budget.Input: changes = [3, -2, 2, 0, -1], budget = 2
Output: 6| Start hub | Length | Hubs served | Net change |
|---|---|---|---|
| 2 | 1 | 2 | 2 |
| 2 | 2 | 2, 3 | 2 |
| 3 | 3 | 3, 4, 0 | 2 |
| 4 | 2 | 4, 0 | 2 |
| 4 | 4 | 4, 0, 1, 2 | 2 |
| any | 5 | all five hubs | 2 |
Three of the six runs pass the last hub. The whole loop sums to 2, and it counts once.
Input: changes = [5], budget = 5
Output: 1One hub is the whole loop.
Input: changes = [0, 0, 0], budget = 0
Output: 7There are 3 runs of length 1, 3 runs of length 2, and the whole loop once.
1 ≤ changes.length ≤ 100,000 (hubs)-1,000 ≤ changes[i] ≤ 1,000-1,000,000,000 ≤ budget ≤ 1,000,000,000There are about 10,000,000,000 runs, one for each start and each length below n. Adding up each run one by one is too slow.
A hash map of prefix sums answers "how many runs end here and match the budget" with one lookup. That is about 100,000 lookups.