Parcel-delivery app~25 min2s · 256 MBtarget O(n + m) time, O(m) spaceclassic twin: lc-567, lc-438window-counts · sliding-window-fixed · hashing
At a delivery hub, the parcels of one batch are loaded onto the conveyor together, but in any order. A scanner at the end of the belt records the code of every parcel that passes. A batch can hold several parcels with the same code, such as three boxes of one product.
The audit team checks that batches stay together on the belt. For a given batch, they want every position in the scan stream where the whole batch passed back to back. That means exactly the batch's codes, each as many times as in the batch, in any order.
Write batch_positions(scans, batch).
scans[i] is the code of the parcel recorded at position i, in order.batch lists the codes in the batch, in any order. A code can appear more than once.len(batch) consecutive scans matches when it holds exactly the codes of batch, each the same number of times, in any order.batch is longer than scans.Input: scans = [4, 2, 4, 9, 2, 2, 4, 4, 2], batch = [2, 4, 4]
Output: [0, 5, 6]The batch needs code 2 once and code 4 twice, so a window matches when matched reaches 2.
| right | Joins | Leaves | Window | Counts of 2 and 4 | matched | Recorded |
|---|---|---|---|---|---|---|
| 0 | 4 | none | 4 | 2→0, 4→1 | 0 | not yet |
| 1 | 2 | none | 4, 2 | 2→1, 4→1 | 1 | not yet |
| 2 | 4 | none | 4, 2, 4 | 2→1, 4→2 | 2 | start 0 |
| 3 | 9 | 4 | 2, 4, 9 | 2→1, 4→1 | 1 | no |
| 4 | 2 | 2 | 4, 9, 2 | 2→1, 4→1 | 1 | no |
| 5 | 2 | 4 | 9, 2, 2 | 2→2, 4→0 | 0 | no |
| 6 | 4 | 9 | 2, 2, 4 | 2→2, 4→1 | 0 | no |
| 7 | 4 | 2 | 2, 4, 4 | 2→1, 4→2 | 2 | start 5 |
| 8 | 2 | 2 | 4, 4, 2 | 2→1, 4→2 | 2 | start 6 |
The window 2, 2, 4 at start 4 has the right codes but the wrong counts. The matches at 5 and 6 overlap.
Input: scans = [6, 1, 1, 6], batch = [1, 6, 6]
Output: []Both windows hold codes 1 and 6, but each has two 1s and one 6. The batch needs one 1 and two 6s.
Input: scans = [5, 8], batch = [8, 5, 5]
Output: []A batch of 3 parcels cannot pass in a stream of 2 scans.
1 ≤ scans.length ≤ 10^5 (about 333 days of scans at an average hub, which handles 300 parcels a day)1 ≤ scans[i] ≤ 10^61 ≤ batch.length ≤ 10^51 ≤ batch[i] ≤ 10^6Sorting every window and comparing it with the sorted batch costs (n − m + 1) windows × m log m, where m is the batch size. Near m = 50,000, copying the windows alone is about 2.5 × 10^9 steps, before any sorting. Aim for O(n + m).
The batch can be as long as the stream, so comparing two full count maps at every window is also too slow. You need a check that costs O(1) per window.