Minimum Swaps to Group All 1's Together II

Medium Topics Company Tags

Treat nums as a circular binary array: its last and first entries are neighbors. You may swap any two positions, even if they are not adjacent. Return the fewest swaps needed to put all the 1 entries into one consecutive circular block. If there are no ones, return 0.

Example 1:

Input: nums = [1,0,0,1]

Output: 0

Explanation: The two ones at the ends are neighbors in the circular array, so they already form one circular block.

Example 2:

Input: nums = [1,0,1,0]

Output: 1

Explanation: Swap the entries at indices 1 and 2 to obtain [1,1,0,0]. The ones were not together initially, so one swap is necessary.

Example 3:

Input: nums = [0]

Output: 0

Explanation: There are no ones to bring together, so no swaps are needed.

Constraints:

  • 1 <= nums.length <= 100000
  • 0 <= nums[i] <= 1


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.