Skip to content

Latest commit

 

History

History
52 lines (37 loc) · 1.23 KB

_2134. Minimum Swaps to Group All 1's Together II.md

File metadata and controls

52 lines (37 loc) · 1.23 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : August 02, 2024

Last updated : August 02, 2024


Related Topics : Array, Sliding Window

Acceptance Rate : 65.54 %


Solutions

Python

class Solution:
    def minSwaps(self, nums: List[int]) -> int:
        totalOnes = nums.count(1)
        if not totalOnes :
            return 0

        oneCount = nums[:totalOnes].count(1)
        zeroCount = totalOnes - oneCount
        minMoves = zeroCount

        for i, nxtVal in enumerate(nums[totalOnes:] + nums[:totalOnes], totalOnes) :
            if nxtVal :
                oneCount += 1
            else :
                zeroCount += 1

            if nums[i - totalOnes] :
                oneCount -= 1
            else :
                zeroCount -= 1

            minMoves = min(minMoves, zeroCount)

        return minMoves