Minimum Number of K Consecutive Bit Flips

Hard

Topics
ArrayBit ManipulationSliding WindowPrefix Sum

You are given a binary array nums and an integer target (the flip window length k). In one operation you choose a contiguous subarray of length exactly k and flip every bit in it. Return the minimum number of operations needed to make every element 1, or -1 if it is impossible.

Example 1

001102
Input:  nums = [0,1,0], target = 1
Output: 2

Example 2

101102
Input:  nums = [1,1,0], target = 2
Output: -1

Example 3

0001021304151607
Input:  nums = [0,0,0,1,0,1,1,0], target = 3
Output: 3

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= target <= nums.length
  • nums[i] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Scanning left to right, the decision at index i is forced: once you pass i, no later window can touch it, so if its effective value is 0 you must flip a window starting exactly here. There is no choice to search over, which is why a greedy sweep is exact.

The only difficulty is knowing the effective value at i — the original bit flipped once per window still covering it. Re-flipping the array per window is O(n·k). Instead keep a running count of active windows and consult its parity: a difference array records where each window's influence expires, so the running count is maintained in O(1) per step.

If a flip is needed but the window would run off the end, no later window can fix this bit either, so the answer is -1.

Approach

  1. Keep a running flip count and a difference array of expiries.
  2. At each index, add the expiries landing here to flip.
  3. The effective bit is (nums[i] + flip) % 2; if it is 1, move on.
  4. If it is 0, fail when i + k > n; otherwise count a flip, increment flip, and schedule an expiry at i + k.

Dry Run

nums = [0,0,0,1,0,1,1,0]   k = 3

  i  nums[i]  active flips  effective  action
  0  0        1             0          flip the window [0,2]
  1  0        1             1          already 1, move on
  2  0        1             1          already 1, move on
  3  1        0             1          the [0,2] window expired here
  4  0        1             0          flip the window [4,6]
  5  1        2             0          flip the window [5,7]
  6  1        2             1          already 1
  7  0        1             1          already 1

answer 3

  [1,1,0] with k = 2 -> -1: index 2 needs a flip but [2,3] runs off the end

Complexity

  • Time — O(n): one pass with constant work per index.
  • Space — O(n) for the difference array. A circular buffer of size k brings it to O(k), and tracking the expiry by overwriting nums in place brings it to O(1) — both worth mentioning once the clean version is on the board.

Common Pitfalls

  • Actually flipping the window each time. That is O(n·k), which at 10⁵ × 10⁵ does not finish.
  • Tracking the number of active flips but testing it directly rather than its parity. Two overlapping flips cancel, so only flip % 2 matters — and index 5 above, with two active windows, is exactly that case.
  • Forgetting to decrement when a window expires, so the parity drifts and every bit past the first window is misread.
  • Returning -1 as soon as a window would overrun, even when the current bit is already 1. The check belongs inside the "needs a flip" branch.
  • Trying to search over which windows to flip. The leftmost unsatisfied bit forces the window that starts there, so there is nothing to choose.
  • Scanning right to left. It works by symmetry but the forced-choice argument is cleaner in one direction, and mixing the two is where off-by-ones come from.

Full Solution — all languages

class Solution:
    def minKBitFlips(self, nums, target):
        n = len(nums)
        diff = [0] * (n + 1)
        flip = 0
        res = 0
        for i in range(n):
            flip += diff[i]
            if (nums[i] + flip) % 2 == 0:
                if i + target > n:
                    return -1
                res += 1
                flip += 1
                diff[i + target] -= 1
        return res
SensAI
Beta
Tap the mic to stop voice mode