Online store~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1151sliding-window-fixed
An online store keeps its stock in a long row of bins in a warehouse. Each bin holds one kind of item, and an order system marks every bin as ready to ship (1) or not ready (0).
A picker walks the row once to collect the ready bins, and walking is slow when the ready bins are far apart. So a robot arm may swap the contents of any two bins, and each swap takes the same time. After the swaps, all ready bins must sit side by side in one block.
The team wants the smallest number of swaps that achieves this. The block may start at any position in the row.
Write fewest_swaps_to_group(bins).
bins[i] is 1 when bin i is ready to ship and 0 otherwise.Input: bins = [1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0]
Output: 2The row has 6 ready bins, so the final block is 6 bins wide. Every 0 inside the chosen block needs one swap with a 1 outside it, so you want the block that already holds the most 1s. Slide a window of width 6, dropping the bin that leaves and adding the bin that enters.
| start | Leaves | Enters | Ready bins in the window | Most so far |
|---|---|---|---|---|
| 0 | 3 | 3 | ||
| 1 | 1 | 1 | 3 | 3 |
| 2 | 0 | 1 | 4 | 4 |
| 3 | 1 | 0 | 3 | 4 |
| 4 | 0 | 1 | 4 | 4 |
| 5 | 0 | 0 | 4 | 4 |
The best window holds 4 of the 6 ready bins, so 6 - 4 = 2 swaps are enough.
Input: bins = [0, 0, 0]
Output: 0There are no ready bins, so nothing needs to move.
Input: bins = [1, 1, 0, 1]
Output: 1The three ready bins need a window of width 3. The window at the left holds 2 of them, and the window at the right holds 2, so one swap is needed.
1 ≤ bins.length ≤ 100,000 (bins in the row)bins[i] is 0 or 1Counting the ready bins in every window from scratch costs about n × w steps, where w is the number of ready bins. With n = 100,000 and w = 50,000 that is 2.5 × 10^9, far over the limit. Aim for O(n).
The answer is at most n, so it fits in a 32-bit integer.