#3191

Minimum Operations to Make Binary Array Elements Equal to One I

Medium
ArrayBit ManipulationQueueSliding WindowPrefix SumGreedySliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a greedy strategy to flip elements as we encounter them. By processing the array in a single pass, we can efficiently determine the minimum number of flips needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a counter for operations and a variable to track the current state of flips.
  2. 2Step 2: Iterate through the array from index 0 to n-1.
  3. 3Step 3: If the current element is 0 and the current state of flips is even (indicating it appears as 0), flip the next three elements and increment the operation counter.
  4. 4Step 4: Adjust the current state of flips accordingly.
solution.py14 lines
1# Full working Python code
2
3def min_operations(nums):
4    operations = 0
5    flips = 0
6    n = len(nums)
7    for i in range(n):
8        if (nums[i] + flips) % 2 == 0:
9            if i + 2 < n:
10                flips += 1
11                operations += 1
12            else:
13                return -1
14    return operations

Complexity note: This complexity is optimal as we only traverse the array once, making it linear in terms of time.

  • 1Flipping three consecutive elements can change the parity of the elements, which is crucial for determining the number of operations.
  • 2The greedy approach allows us to minimize operations by making decisions based on the current state of the array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.