Parcel-delivery app~35 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-2516sliding-window-variable · window-counts
A delivery truck has loading doors at both ends. Its parcels stand in one line from the front door to the back door. Each parcel has a type: 1 for fragile, 2 for standard and 3 for bulky.
At a sorting hub, the truck must drop off at least k parcels of each type for the next route. Staff can only reach the parcel nearest each door, so they unload some from the front and some from the back. Every parcel moved costs time, so the hub wants the fewest parcels unloaded.
Some trucks do not carry k parcels of every type, and then no split works.
Write fewest_unloads(types, k).
types[i] is the type of the parcel at position i, counted from the front door: 1 (fragile), 2 (standard) or 3 (bulky).a parcels and the last b parcels, for any a ≥ 0 and b ≥ 0 with a + b ≤ n, where n is the length of types.k parcels of each of the three types.a + b.k is 0, return 0: nothing needs to be unloaded.k parcels of some type, return -1.Input: types = [2, 3, 2, 3, 2, 2, 1, 1, 2, 3], k = 2
Output: 6The truck holds 2 fragile, 5 standard and 3 bulky parcels. The parcels that stay form one window, and it may keep at most 0 fragile, 3 standard and 1 bulky parcel. The window grows on the right, and parcels leave on the left while the joining type is over its limit.
| right | Joins | Leaves | left after | Window that stays | Fragile, standard, bulky kept | Longest |
|---|---|---|---|---|---|---|
| 0 | 2 | none | 0 | 2 | 0, 1, 0 | 1 |
| 1 | 3 | none | 0 | 2, 3 | 0, 1, 1 | 2 |
| 2 | 2 | none | 0 | 2, 3, 2 | 0, 2, 1 | 3 |
| 3 | 3 | 2, 3 | 2 | 2, 3 | 0, 1, 1 | 3 |
| 4 | 2 | none | 2 | 2, 3, 2 | 0, 2, 1 | 3 |
| 5 | 2 | none | 2 | 2, 3, 2, 2 | 0, 3, 1 | 4 |
| 6 | 1 | 2, 3, 2, 2, 1 | 7 | empty | 0, 0, 0 | 4 |
| 7 | 1 | 1 | 8 | empty | 0, 0, 0 | 4 |
| 8 | 2 | none | 8 | 2 | 0, 1, 0 | 4 |
| 9 | 3 | none | 8 | 2, 3 | 0, 1, 1 | 4 |
The longest window is positions 2 to 5, 2, 3, 2, 2. So the hub unloads the first 2 parcels and the last 4: 2, 3 and 1, 1, 2, 3, two of each type.
Input: types = [1, 2, 2, 1, 2], k = 1
Output: -1The truck carries no bulky parcel, so no split collects one.
Input: types = [1, 1, 2, 1, 3], k = 1
Output: 3The last three parcels, 2, 1, 3, hold one of each type. Nothing comes from the front.
1 ≤ types.length ≤ 10^5types[i] is 1, 2 or 30 ≤ k ≤ 10^5Trying every number of front parcels, then adding back parcels until each type has k, is O(n^2). On the large test stress-random, that is about 4.1 × 10^9 steps. Aim for O(n).
There are only three types, so the counts fit in an array of size 4, with index 0 unused. The extra space is then O(1).