Minimum Number of K Consecutive Bit Flips

hard bit manipulation greedy difference array

Problem

You are given a binary array nums and an integer k. A k-bit flip chooses a contiguous subarray of length exactly k and flips every bit in it (0 becomes 1, 1 becomes 0). Return the minimum number of k-bit flips needed to make the array contain no 0s. If it is not possible, return -1.

Inputnums = [0, 0, 0, 1, 0, 1, 1, 0], k = 3
Output3
Flip at index 0 → [1,1,1,1,0,1,1,0], flip at index 4 → [1,1,1,1,1,0,0,0], flip at index 5 → [1,1,1,1,1,1,1,1].

def min_k_bit_flips(nums, k):
    n = len(nums)
    diff = [0] * (n + 1)
    flipped = 0
    ans = 0
    for i in range(n):
        flipped += diff[i]
        if (nums[i] + flipped) % 2 == 0:
            if i + k > n:
                return -1
            ans += 1
            flipped += 1
            diff[i + k] -= 1
    return ans
function minKBitFlips(nums, k) {
  const n = nums.length;
  const diff = new Array(n + 1).fill(0);
  let flipped = 0, ans = 0;
  for (let i = 0; i < n; i++) {
    flipped += diff[i];
    if ((nums[i] + flipped) % 2 === 0) {
      if (i + k > n) return -1;
      ans++;
      flipped++;
      diff[i + k]--;
    }
  }
  return ans;
}
class Solution {
    public int minKBitFlips(int[] nums, int k) {
        int n = nums.length;
        int[] diff = new int[n + 1];
        int flipped = 0, ans = 0;
        for (int i = 0; i < n; i++) {
            flipped += diff[i];
            if ((nums[i] + flipped) % 2 == 0) {
                if (i + k > n) return -1;
                ans++;
                flipped++;
                diff[i + k]--;
            }
        }
        return ans;
    }
}
int minKBitFlips(vector<int>& nums, int k) {
    int n = nums.size();
    vector<int> diff(n + 1, 0);
    int flipped = 0, ans = 0;
    for (int i = 0; i < n; i++) {
        flipped += diff[i];
        if ((nums[i] + flipped) % 2 == 0) {
            if (i + k > n) return -1;
            ans++;
            flipped++;
            diff[i + k]--;
        }
    }
    return ans;
}
Time: O(n) Space: O(n)