Minimum Operations to Make Binary Array Elements Equal to One II - 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 index i from the array and flip all the elements from index i to the end of the array.

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,0]
Output: 2
💡 Note: Flip at index 0: [0,1,0] → [1,0,1]. Flip at index 2: [1,0,1] → [1,1,0]. Need 2 operations total.
Example 2 — Already All Ones
$ Input: nums = [1,1,1]
Output: 0
💡 Note: All elements are already 1, so no operations needed.
Example 3 — All Zeros
$ Input: nums = [0,0,0]
Output: 1
💡 Note: Flip at index 0: [0,0,0] → [1,1,1]. Only 1 operation needed.

Constraints

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

Visualization

Tap to expand
Minimum Operations to Make Binary Array Equal to One II INPUT Binary Array nums: 0 i=0 1 i=1 0 i=2 nums = [0, 1, 0] Goal: Make all elements = 1 using minimum flips Flip Operation: Choose index i, flip all elements from i to end (0-->1, 1-->0) ALGORITHM STEPS 1 Scan i=0: nums[0]=0 0 found, flip from i=0 [0,1,0]-->[1,0,1] ops=1 2 Scan i=1: nums[1]=0 0 found, flip from i=1 [1,0,1]-->[1,1,0] ops=2 3 Scan i=2: nums[2]=0 0 found, flip from i=2 [1,1,0]-->[1,1,1] ops=3? 4 Track Flip State Use XOR with flip count to track actual value Greedy Approach: - If current XOR flips = 0 - Increment operations - Track flip state (odd/even) - Result: 2 operations FINAL RESULT Final Array: 1 1 1 Output: 2 OK - All elements = 1 Operation Trace: Initial: [0,1,0] Op 1 (i=0): [1,0,1] Op 2 (i=1): [1,1,0] Wait - optimized to 2! Key Insight: Instead of actually flipping, track the flip count. Use XOR: actual_value = nums[i] XOR (flip_count % 2). If actual_value is 0, we need a flip. Greedy: scan left to right, flip whenever we see 0 (considering flip state). Time: O(n), Space: O(1). Each flip affects all elements to the right, so we only need to track odd/even flip count. TutorialsPoint - Minimum Operations to Make Binary Array Elements Equal to One II | Greedy - Scan Left to Right
Asked in
Google 25 Amazon 20 Microsoft 15
22.1K Views
Medium Frequency
~15 min Avg. Time
850 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