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 Equal to One INPUT Binary Array nums: 0 i=0 1 i=1 1 i=2 1 i=3 0 i=4 0 i=5 Length: n = 6 Target: All elements = 1 Operation: Choose 3 consecutive elements Flip all 3: 0-->1, 1-->0 = 0 (needs flip) = 1 (target) ALGORITHM STEPS 1 Scan Left-to-Right Find first 0 at index i 2 Flip [i, i+1, i+2] Toggle 3 consecutive bits 3 Increment Counter operations++ 4 Repeat Until Done Or return -1 if impossible Execution Trace: Op1: Flip[0,1,2] [0,1,1,1,0,0]-->[1,0,0,1,0,0] Op2: Flip[1,2,3] [1,0,0,1,0,0]-->[1,1,1,0,0,0] Op3: Flip[3,4,5] [1,1,1,0,0,0]-->[1,1,1,1,1,1] All 1s! Done. FINAL RESULT Final Array State: 1 1 1 1 1 1 OUTPUT 3 Minimum Operations: 3 Summary: - Operation 1: i=0 - Operation 2: i=1 - Operation 3: i=3 Key Insight: Greedy approach works optimally: When we encounter a 0, we MUST flip it. Flipping earlier doesn't help later 0s. Time Complexity: O(n). Returns -1 if any 0 remains in last 2 positions. TutorialsPoint - Minimum Operations to Make Binary Array Elements Equal to One I | Greedy Left-to-Right
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