VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-bit-flips-such-that-every-k-consecutive-bits-contain-at-least-one-set-bit/

⇱ Minimum bit flips such that every K consecutive bits contain at least one set bit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum bit flips such that every K consecutive bits contain at least one set bit

Last Updated : 15 Jul, 2025

Given a binary string S, and an integer K, the task is to find the minimum number of flips required such that every substring of length K contains at least one '1'.
Examples: 
 

Input: S = "10000001" K = 2 
Output:
Explanation: 
We need only 3 changes in string S ( at position 2, 4 and 6 ) so that the string contain at least one '1' in every sub-string of length 2.
Input: S = "000000" K = 3 
Output:
Explanation: 
We need only 3 changes in string S ( at position 2 and 5 ) so that the string contain at least one '1' in every sub-string of length 3.
Input: S = "111010111" K = 2 
Output:
 


 


Naive Approach: 
To solve the problem, the simplest approach is to iterate for each substring of length K and find the minimum number of flips required to satisfy the given condition. 
Time complexity: O(N * K)

Space Complexity: O(1)


Efficient Approach: 
The idea is to use Sliding Window Approach. 
 

  • Set a window size of K.
  • Store the index of previous appearance of 1.
  • If the current bit is unset and the difference between the current ith bit and the previous set bit exceeds K, set the current bit and store the current index as that of the previous set bit and proceed further.


Below is the implementation of the above approach:
 


Output: 
3

 

Time complexity: O(N + K) 
Auxiliary Space: O(1)
 

Comment