Minimum Operations to Make Binary Array Elements Equal to One I - Problem

You are given a binary array nums. You can do the following operation on the array any number of times (possibly zero):

Choose any 3 consecutive elements from the array and flip all of them. Flipping an element means changing its value from 0 to 1, and from 1 to 0.

Return the minimum number of operations required to make all elements in nums equal to 1. If it is impossible, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,1,1,0,0]
Output: 3
💡 Note: Start with [0,1,1,1,0,0]. Flip positions 0-2: [1,0,0,1,0,0]. Flip positions 1-3: [1,1,1,0,0,0]. Flip positions 3-5: [1,1,1,1,1,1]. Total: 3 operations.
Example 2 — Impossible Case
$ Input: nums = [0,1,1,1]
Output: -1
💡 Note: Array length is 4. Last element is 1, but positions 1,2 are both 1. If we flip positions 1-3, we get [0,0,0,0]. Cannot make all 1s.
Example 3 — All Ones
$ Input: nums = [1,1,1]
Output: 0
💡 Note: All elements are already 1, no operations needed.

Constraints

  • 3 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Minimum Operations to Make Binary Array Elements Equal to OneInput:011100Flip 3 consecutiveGoal:111111Strategy: Greedy left-to-right scanWhen we see 0, flip it with next 2 elementsOutput: 3 (minimum operations needed)
Understanding the Visualization
1
Input Array
Binary array with 0s and 1s that need to become all 1s
2
3-Element Flips
Can only flip 3 consecutive elements at once
3
Minimum Operations
Find fewest flips to make all elements 1, or return -1 if impossible
Key Takeaway
🎯 Key Insight: Process left to right - when you encounter a 0, you must flip it immediately since you can't go back
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen