Minimum Number of K Consecutive Bit Flips - Problem
You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.
A subarray is a contiguous part of an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [0,1,0], k = 1
›
Output:
2
💡 Note:
Flip nums[0] to get [1,1,0], then flip nums[2] to get [1,1,1]. Total 2 flips needed.
Example 2 — Larger K
$
Input:
nums = [1,1,0], k = 2
›
Output:
-1
💡 Note:
No matter how we flip, we cannot make all elements 1. The last element cannot be covered by any valid 2-flip.
Example 3 — Multiple Flips
$
Input:
nums = [0,0,0,1,0,1,1,0], k = 3
›
Output:
3
💡 Note:
Flip [0,0,0] to [1,1,1], flip [0,1,1] to [1,0,0], flip [0,0,x] at the end. Total 3 flips.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary array [0,1,0] with k=1
2
Process
Apply minimum flips to make all bits 1
3
Output
Return minimum number of flips: 2
Key Takeaway
🎯 Key Insight: Track flip effects efficiently using differential arrays instead of simulating each flip operation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code