![]() |
VOOZH | about |
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: 3
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: 2
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: 0
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.
Below is the implementation of the above approach:
3
Time complexity: O(N + K)
Auxiliary Space: O(1)