All problems
0645MediumArraySliding Window

Gathering The Boxes Into One Block

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1151Minimum Swaps to Group All 1's Together

This 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.

Examples

Example 1

Input
slots = [1, 0, 1, 1, 0, 1, 1]
Output
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

Input
slots = [0, 0, 1, 1, 1]
Output
0

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

Input
slots = [1, 0, 1, 0, 1, 0, 1, 0, 1]
Output
2

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.

Constraints

  • 1 <= slots.length <= 10^5
  • slots[i] is either 0 or 1.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def min_swaps(slots: list[int]) -> int:
Java
public int minSwaps(int[] slots)
September 7
Apply