Minimum Swaps to Group All 1's Together II

A swap is defined as taking two distinct positions in an array and swapping the values in them.

A circular array is defined as an array where we consider the first element and the last element to be adjacent.

Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.

Example 1
Inputnums = [0,1,0,1,1,0,0]
Output1
There is no way to group all 1's together with 0 swaps, but they can be grouped together with 1 swap.
Example 2
Inputnums = [0,1,1,1,0,0,1,1,0]
Output2
There is no way to group all 1's together with 0 or 1 swaps, but they can be grouped together with 2 swaps.

Constraints

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

Asked at 10 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate