Problem Description
Given a binary string s and an integer k, we need to count the number of non-empty substrings such that the substring satisfies the k-constraint. A substring satisfies the k-constraint if either the number of 0's in it is at most k or the number of 1's in it is at most k.
Key Insights
- The string only contains characters '0' and '1', and its maximum length is 50, so an O(n²) brute force approach is acceptable.
- A substring satisfies the k-constraint if at least one of its character counts (zeros or ones) is ≤ k.
- By iterating over all possible substrings and updating counts as we extend the substring, we can decide whether each substring satisfies the given constraint.
- Although advanced sliding window techniques exist, here a straightforward nested loop with counters is simple and efficient due to the small constraints.
Space and Time Complexity
Time Complexity: O(n²), where n is the length of the string. Space Complexity: O(1), as only a few integer counters are maintained.
Solution
The solution iterates over every possible substring by using two nested loops. For each substring, we maintain running counts for 0's and 1's. If either count remains less than or equal to k, the substring is valid and we increment our count. This approach avoids recalculating the character counts for each substring from scratch by updating them as the substring extends.