Parcel-delivery app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-167, lc-1opposite-ends · two-pointers
A delivery truck is about to leave a hub with some spare capacity. Your team lead wants the dispatch screen to suggest two waiting parcels that fill that space exactly, so the truck leaves full.
The loading list is sorted by weight, from the lightest parcel to the heaviest, and no two parcels weigh the same. Sometimes several pairs fit. The loaders then want the pair that starts with the lightest parcel, because light parcels wait longest. Sometimes no pair fits, and the screen says so.
Write fill_pair(weights, spare).
weights[i] is the weight of parcel i in grams. The list is strictly increasing: each weight is larger than the one before it.spare is the truck's spare capacity in grams.[i, j] with i < j and weights[i] + weights[j] == spare.i.[-1, -1].Input: weights = [3000, 5000, 8000, 12000, 14000, 20000], spare = 22000
Output: [2, 4]| left | right | weights[left] | weights[right] | Total | Compared with 22000 | Move |
|---|---|---|---|---|---|---|
| 0 | 5 | 3000 | 20000 | 23000 | too heavy | rule out right: right becomes 4 |
| 0 | 4 | 3000 | 14000 | 17000 | too light | rule out left: left becomes 1 |
| 1 | 4 | 5000 | 14000 | 19000 | too light | rule out left: left becomes 2 |
| 2 | 4 | 8000 | 14000 | 22000 | exact | return [2, 4] |
The 20000 g parcel overfills the truck even with the lightest parcel, so it can never be part of the answer.
Input: weights = [2000, 5000, 7000, 10000, 13000, 18000], spare = 20000
Output: [0, 5]Two pairs fill the space: 2000 + 18000 and 7000 + 13000. The pair with the smaller i wins.
Input: weights = [3000, 6000, 9000, 12000], spare = 10000
Output: [-1, -1]The possible totals are 9000, 12000, 15000, 15000, 18000 and 21000. None of them is 10000.
2 ≤ weights.length ≤ 10^51 ≤ weights[i] ≤ 10^6 (one tonne), and weights[i] < weights[i + 1] for every i2 ≤ spare ≤ 2 × 10^6Trying every pair costs n × (n − 1) / 2 checks. At n = 10^5 that is about 5 × 10^9: far over the budget of about 10^8 simple operations a second. Aim for O(n).
The list is already sorted, and the problem says so for a reason. On sorted data, one pointer at each end can rule out a parcel at every step.