Minimum Number of K Consecutive Bit Flips - Problem

You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.

Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,0], k = 1
Output: 2
💡 Note: Flip nums[0] to get [1,1,0], then flip nums[2] to get [1,1,1]. Total 2 flips needed.
Example 2 — Larger K
$ Input: nums = [1,1,0], k = 2
Output: -1
💡 Note: No matter how we flip, we cannot make all elements 1. The last element cannot be covered by any valid 2-flip.
Example 3 — Multiple Flips
$ Input: nums = [0,0,0,1,0,1,1,0], k = 3
Output: 3
💡 Note: Flip [0,0,0] to [1,1,1], flip [0,1,1] to [1,0,0], flip [0,0,x] at the end. Total 3 flips.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Minimum Number of K Consecutive Bit Flips INPUT nums array: 0 idx 0 1 idx 1 0 idx 2 k = 1 Goal: Make all bits = 1 using minimum flips 0s need to be flipped ! ! nums=[0,1,0], k=1 ALGORITHM STEPS 1 Use diff array Track flip effects 2 i=0: nums[0]=0 Flip! count=1 3 i=1: nums[1]=1 Already 1, skip 4 i=2: nums[2]=0 Flip! count=2 Diff Array Tracking: flips: [1, 0, 1, 0] curr_flips tracks state at each position O(n) time complexity Greedy left-to-right scan FINAL RESULT After 2 flips: 1 OK 1 OK 1 OK Output: 2 Minimum flips needed to make all 1s Flip Operations: Flip 1: idx 0 (0-->1) Flip 2: idx 2 (0-->1) Key Insight: The differential array optimization tracks flip effects efficiently. Instead of actually flipping k bits, we mark the start and end of each flip window. This reduces time complexity from O(n*k) to O(n). Greedy approach: flip at first 0 encountered, as delaying never helps. TutorialsPoint - Minimum Number of K Consecutive Bit Flips | Differential Array Optimization
Asked in
Google 25 Facebook 18 Amazon 12
28.5K Views
Medium Frequency
~35 min Avg. Time
892 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