Minimum Number of K Consecutive Bit Flips

HardGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You have a binary array nums and an integer k. In one operation you pick a window of exactly k **consecutive** elements and flip every bit in it (0 becomes 1, 1 becomes 0). Return the **minimum** number of operations needed to make every element equal to 1, or -1 if it is impossible. Target O(n) time: simulating each flip element by element costs O(n * k).

Examples

Input: nums = [0,0,1,1,0,0], k = 2
Output: 2
Flip indices 0-1, then indices 4-5.
Input: nums = [1,0,1], k = 2
Output: -1
The only windows are `[0,1]` and `[1,2]`. Flipping either one, or both, never yields all ones.
Input: nums = [0,1,0], k = 1
Output: 2
With `k = 1`, flip the two zeros individually.

Constraints

  • `1 <= nums.length <= 10^5`
  • `1 <= k <= nums.length`
  • `nums[i]` is `0` or `1`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems