Minimum Number of K Consecutive Bit Flips

Hard Topics Company Tags

In one operation, choose exactly k consecutive elements of the binary array nums and flip each bit: zero becomes one, and one becomes zero. Return the fewest operations needed to make every element one, or -1 if this is impossible.

Example 1:

Input: nums = [0,0,1,0,0]
k = 2

Output: 2

Explanation: Flip the first two bits and then the last two bits. Every bit becomes one after two operations. One operation cannot change all four zeros.

Example 2:

Input: nums = [1,0,1]
k = 2

Output: -1

Explanation: Flipping either available pair also changes an endpoint from one to zero. Flipping both pairs leaves the middle bit zero, so no sequence works.

Example 3:

Input: nums = [1,1,1]
k = 3

Output: 0

Explanation: Every bit is already one, so no operations are needed.

Constraints:

  • 1 <= nums.length <= 100000
  • 0 <= nums[i] <= 1
  • 1 <= k <= nums.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.