java.lang.Object
g2101_2200.s2134_minimum_swaps_to_group_all_1s_together_ii.Solution

public class Solution extends Object
2134 - Minimum Swaps to Group All 1&rsquo;s Together II.<p>Medium</p> <p>A <strong>swap</strong> is defined as taking two <strong>distinct</strong> positions in an array and swapping the values in them.</p> <p>A <strong>circular</strong> array is defined as an array where we consider the <strong>first</strong> element and the <strong>last</strong> element to be <strong>adjacent</strong>.</p> <p>Given a <strong>binary</strong> <strong>circular</strong> array <code>nums</code>, return <em>the minimum number of swaps required to group all</em> <code>1</code><em>&rsquo;s present in the array together at <strong>any location</strong></em>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums = [0,1,0,1,1,0,0]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong> Here are a few of the ways to group all the 1&rsquo;s together:</p> <p>[0,0,1,1,1,0,0] using 1 swap.</p> <p>[0,1,1,1,0,0,0] using 1 swap.</p> <p>[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).</p> <p>There is no way to group all 1&rsquo;s together with 0 swaps.</p> <p>Thus, the minimum number of swaps required is 1.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums = [0,1,1,1,0,0,1,1,0]</p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong> Here are a few of the ways to group all the 1&rsquo;s together:</p> <p>[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).</p> <p>[1,1,1,1,1,0,0,0,0] using 2 swaps.</p> <p>There is no way to group all 1&rsquo;s together with 0 or 1 swaps.</p> <p>Thus, the minimum number of swaps required is 2.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> nums = [1,1,0,0,1]</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong> All the 1&rsquo;s are already grouped together due to the circular property of the array.</p> <p>Thus, the minimum number of swaps required is 0.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= nums.length <= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • minSwaps

      public int minSwaps(int[] nums)