Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 19, 2025 21:16
Show Gist options
  • Save Ifihan/771012ebdb7b949e3d3534fc34c1991e to your computer and use it in GitHub Desktop.
Save Ifihan/771012ebdb7b949e3d3534fc34c1991e to your computer and use it in GitHub Desktop.
Minimum Operations to Make Binary Array Elements Equal to One I

Question

Approach

In this approach, I iterate through the array and flip the first encountered '0' along with the next two elements. This ensures I always maximize the number of '1's as it moves forward. If any '0' remains in the last two positions, it is impossible to make all elements '1'.

Implementation

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        n = len(nums)
        operations = 0
        
        for i in range(n - 2):
            if nums[i] == 0:
                nums[i] ^= 1
                nums[i + 1] ^= 1
                nums[i + 2] ^= 1
                operations += 1
        
        if nums[-2] == 0 or nums[-1] == 0:
            return -1
        
        return operations

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment