Minimum Number of K Consecutive Bit Flips
Given a binary array nums and an integer k, you may pick any subarray of exactly k consecutive elements and flip every bit in it (0 becomes 1, 1 becomes 0), any number of times. Return the minimum number of flips needed to make every element 1, or -1 if it is impossible. Track how many active flips still affect the current position with a running counter instead of rewriting every element in the window.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
- numsi is 0 or 1
Example
nums = [0,1,0], k = 12Explanation With k = 1 each flip toggles a single bit; flip index 0 and index 2 to get [1,1,1].
In plain terms
- Subarray
- A run of elements taken right out of the array as-is, next to each other in order — not values picked out from anywhere in the array.
A running counter tracks active flips
Position 0 is 0 with no active flips — start flip #1 here.
What happens in this step
i=0: currFlips = 0 (diff[0]=0) (nums[0] + currFlips) % 2 = (0+0)%2 = 0 → still a 0, must flip here flips: 0→1, currFlips: 0→1, diff[0+k]=diff[1]-- → marks flip #1 ends at i=1
Steps to visualize
- Scan left to right, keeping a running count of flips still active at the current position.
- If the current bit, adjusted for active flips, is still a 0, a new flip must start here.
- Record the flip's end with a marker instead of rewriting all k elements of the window.
- When the marker position is reached later, subtract that flip back out of the running count.
- If a required flip would need to start past the point where k more elements fit, return -1.
- Add up every flip that was started for the final answer.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Position 0 is 0 with no active flips — start flip #1 here.
What happens in this step
i=0: currFlips = 0 (diff[0]=0) (nums[0] + currFlips) % 2 = (0+0)%2 = 0 → still a 0, must flip here flips: 0→1, currFlips: 0→1, diff[0+k]=diff[1]-- → marks flip #1 ends at i=1
Solution
function minKBitFlips(nums, k) {
const n = nums.length;
const diff = new Array(n + 1).fill(0);
let flips = 0;
let currFlips = 0;
for (let i = 0; i < n; i++) {
currFlips += diff[i];
if ((nums[i] + currFlips) % 2 === 0) {
if (i + k > n) return -1;
flips++;
currFlips++;
diff[i + k]--;
}
}
return flips;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [0,1,0], k = 1 | 2 | Docstring example |
nums = [1,1,0], k = 2 | -1 | Impossible — required flip runs past the array end |
nums = [1,1,1], k = 2 | 0 | Already all 1s |
nums = [0,0,0], k = 3 | 1 | k equals array length |
nums = [0], k = 1 | 1 | Minimal single-element array needing a flip |
nums = [1], k = 1 | 0 | Minimal single-element array already satisfied |
nums = [0,0,0,1,0,1,1,0], k = 3 | 3 | Larger hand-verified case with overlapping flips |
nums = [1,0,0,0], k = 4 | -1 | Impossible — not enough room left for the required flip |