Parcel-delivery app~30 min2s · 256 MBtarget O(n log n) time, O(n) spacedp · binary-search
You work on a sorting hub of a freight company. Parcels arrive one at a time on a belt, and each has a weight in grams. The hub has several lanes, and every arriving parcel is pushed onto one lane at once.
To keep the stacks stable, a lane must receive strictly heavier parcels as time goes on. A parcel can only go on a lane whose last parcel is lighter than it, or on an empty lane.
Your team lead asks: "What is the fewest number of lanes that can take the whole belt?" The belt can carry 100,000 parcels.
Write fewest_lanes(weights).
weights[i] is the weight of the parcel that arrives at time i. Weights can repeat.Input: weights = [4, 2, 5, 3, 1]
Output: 3Each parcel goes on the lane whose last parcel is the heaviest one that is still lighter than the new parcel. If there is none, a new lane opens. The last weights of the lanes, from heaviest to lightest, after each parcel:
| Parcel | Placed on | Lane ends |
|---|---|---|
| 4 | new lane | 4 |
| 2 | new lane | 4, 2 |
| 5 | lane 1 | 5, 2 |
| 3 | lane 2 | 5, 3 |
| 1 | new lane | 5, 3, 1 |
Three lanes remain. For example, lane 1 holds 4 and then 5.
Input: weights = [1, 2, 3]
Output: 1Each parcel is heavier than the last, so one lane takes all three.
Input: weights = [3, 3, 3]
Output: 3A lane needs strictly heavier parcels, so equal parcels cannot share a lane. Three parcels need three lanes.
1 ≤ len(weights) ≤ 100,0001 ≤ weights[i] ≤ 1,000,000,000Trying every placement of every parcel is far beyond reach. Even a greedy rule that checks every lane for every parcel makes up to 100,000 × 100,000 / 2 = 5,000,000,000 checks. You need the right lane in about log n steps, so the lanes must be kept in an order that a binary search can use.