You are given a binary string s and an integer k.
A binary string satisfies the k-constraint if either of the following conditions holds:
0's in the string is at most k.1's in the string is at most k.Return an integer denoting the number of substrings of s that satisfy the k-constraint.
Example 1:
Input: s = "10101", k = 1
Output: 12
Explanation:
Every substring of s except the substrings "1010", "10101", and "0101" satisfies the k-constraint.
Example 2:
Input: s = "1010101", k = 2
Output: 25
Explanation:
Every substring of s except the substrings with a length greater than 5 satisfies the k-constraint.
Example 3:
Input: s = "11111", k = 1
Output: 15
Explanation:
All substrings of s satisfy the k-constraint.
Constraints:
1 <= s.length <= 50 1 <= k <= s.lengths[i] is either '0' or '1'.In this approach, we check all possible substrings of the given binary string s. For each substring, we count the number of 0's and 1's, then check if the substring satisfies the k-constraint. This method is straightforward but may be inefficient for longer strings.
This solution iterates through each possible starting index of a substring, then extends the substring as long as it satisfies the k-constraint. If either the number of 0's or 1's exceeds k, we stop extending the substring from that starting index.
C
C++
Java
C#
JavaScript
The time complexity of this brute force approach is O(n2), where n is the length of the string. The space complexity is O(1) as we only use a few extra variables.
This approach utilizes a sliding window technique to optimize counting of valid substrings. We maintain two sliding windows – one for tracking substrings with zeros ≤ k and one for substrings with ones ≤ k. The aim is to adjust the window such that it remains valid and count all substrings possible within each window.
This solution employs a function helper to count valid substrings where either '0' or '1' is ≤ k. It uses a sliding window to adjust the window size dynamically and count all possible substrings within that valid window.
C
C++
Java
C#
JavaScript
The time complexity is O(n) for processing each character, and the space complexity is O(1) due to no additional data structures used.
| Approach | Complexity |
|---|---|
| Brute Force Approach | The time complexity of this brute force approach is O(n2), where n is the length of the string. The space complexity is O(1) as we only use a few extra variables. |
| Sliding Window Approach | The time complexity is O(n) for processing each character, and the space complexity is O(1) due to no additional data structures used. |
Count Substrings That Satisfy K-Constraint I & II | Detailed Explanation | Leetcode 3258 & 3261 • codestorywithMIK • 6,249 views views
Watch 9 more video solutions →Practice Count Substrings That Satisfy K-Constraint I with our built-in code editor and test cases.
Practice on FleetCode