Trains the technique from
LeetCode 1151Minimum Swaps to Group All 1's TogetherThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A storage rail is a row of positions. slots[i] is 1 when position i holds a box and 0 when it is empty.
One swap exchanges the contents of any two positions on the rail; the two positions need not be neighbours. Return the fewest swaps that leave the boxes in one unbroken block, meaning no empty position sits between two boxes. A rail with no boxes, or with only one, already satisfies this.
Example 1
The rail holds 5 boxes. Swapping position 0 with position 4 leaves the boxes on positions 2 through 6 with nothing empty in between, so 1 swap is enough.
Example 2
The 3 boxes at positions 2, 3 and 4 already sit next to each other with no empty position between them, so no swap is needed.
Example 3
The rail holds 5 boxes. Swapping position 0 with position 5, then position 2 with position 7, leaves the boxes on positions 4 through 8 with nothing empty in between, so 2 swaps are enough.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def min_swaps(slots: list[int]) -> int:public int minSwaps(int[] slots)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.