499. Minimum Swaps to Group Packages on a Circular Conveyor Belt
Minimum Swaps to Group Packages on a Circular Conveyor Belt

A warehouse has a circular conveyor belt with n slots numbered 0 to n - 1. Each slot either holds one package or is empty. Because the belt is circular, slot n - 1 is next to slot 0.

In one swap, you can pick any two different slots and exchange their contents. The two slots do not need to be next to each other.

Return the minimum number of swaps needed to group all packages together, so that they occupy consecutive slots on the belt. The group may wrap around from slot n - 1 to slot 0. If the belt has no packages, return 0.

Method Signature

int minSwapsToGroupPackages(List<Integer> belt)

  • belt[i] == 1 means slot i holds a package.
  • belt[i] == 0 means slot i is empty.
  • Returns the minimum number of swaps needed to group all packages together.

Constraints

  • 1 ≤ belt.size() ≤ 100,000
  • belt[i] is either 0 or 1.

Examples

Example 1

minSwapsToGroupPackages(belt = [1, 0, 1, 0, 0, 1, 0])

Output: 1

Explanation:

  • There are 3 packages, in slots 0, 2 and 5.
  • Swap slot 1 (empty) with slot 5 (package). The belt becomes [1, 1, 1, 0, 0, 0, 0].
  • No 3 consecutive slots already hold packages, so at least 1 swap is needed.

Example 2

minSwapsToGroupPackages(belt = [1, 1, 0, 0, 0, 1])

Output: 0

Explanation:

  • There are 3 packages, in slots 5, 0 and 1.
  • Slot 5 is next to slot 0 on the circular belt, so these 3 slots are already consecutive.
  • No swaps are needed.

Example 3

minSwapsToGroupPackages(belt = [0, 1, 0, 1, 1, 0, 1, 0, 0, 1])

Output: 2

Explanation:

  • There are 5 packages, in slots 1, 3, 4, 6 and 9.
  • Swap slot 1 with slot 2. The belt becomes [0, 0, 1, 1, 1, 0, 1, 0, 0, 1].
  • Swap slot 9 with slot 5. The belt becomes [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], and all packages are in slots 2 to 6.
  • Every group of 5 consecutive slots holds at most 3 packages, so at least 2 swaps are needed.

Example 4

minSwapsToGroupPackages(belt = [0, 0, 0])

Output: 0

Explanation:

  • The belt has no packages, so no swaps are needed.


Please use Laptop/Desktop or any other large screen to add/edit code.