LeetCode: Minimum Swaps to Group All 1’s Together Posted on September 3, 2019July 26, 2020 by braindenny Minimum Swaps to Group All 1’s Together Similar Problems: LeetCode: Max Consecutive Ones LeetCode: Max Consecutive Ones II LeetCode: Max Consecutive Ones III LeetCode: Minimum Swaps to Group All 1’s Together CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #slidingwindow Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array. Example 1: Input: [1,0,1,0,1] Output: 1 Explanation: There are 3 ways to group all 1's together: [1,1,1,0,0] using 1 swap. [0,1,1,1,0] using 2 swaps. [0,0,1,1,1] using 1 swap. The minimum is 1. Example 2: Input: [0,0,0,1,0] Output: 0 Explanation: Since there is only one 1 in the array, no swaps needed. Example 3: Input: [1,0,1,0,1,0,0,1,1,0,1] Output: 3 Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1]. Note: 1 <= data.length <= 10^5 0 <= data[i] <= 1 Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: // https://code.dennyzhang.com/minimum-swaps-to-group-all-1s-together // Basic Ideas: fixed size sliding window // We know the size of the final group all 1's // The window can start from any position // Use a sliding window. And the find the minimum count of 0s in the sliding window. // Complexity: Time O(n), Space O(k) func minSwaps(data []int) int { k:=0 for _, v := range data { if v == 1 { k++ } } res := 1<<31-1 count := 0 // sliding window. left: i-k+1, right: i for i:=0; i<len(data); i++ { // move right pointer: add a new element if data[i] == 0 { count++ } // move left pointer: remove the old element if i-k >= 0 { if data[i-k] == 0 { count-- } } // collect result if i-k+1 >= 0 { if count < res { res = count } } } return res } Post Views: 0