Count Substrings That Satisfy K-Constraint II Problem
Description
LeetCode Problem 3261.
You are given a binary string s and an integer k.
You are also given a 2D integer array queries, where queries[i] = [l_i, r_i].
A binary string satisfies the k-constraint if either of the following conditions holds:
- The number of
0's in the string is at mostk. - The number of
1's in the string is at mostk.
Return an integer array answer, where answer[i] is the number of substrings of s[l_i..r_i] that satisfy the k-constraint.
Example 1:
Input: s = "0001111", k = 2, queries = [[0,6]]
Output: [26]
Explanation:
For the query [0, 6], all substrings of s[0..6] = "0001111" satisfy the k-constraint except for the substrings s[0..5] = "000111" and s[0..6] = "0001111".
Example 2:
Input: s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]
Output: [15,9,3]
Explanation:
The substrings of s with a length greater than 3 do not satisfy the k-constraint.
Constraints:
1 <= s.length <= 10^5s[i]is either'0'or'1'.1 <= k <= s.length1 <= queries.length <= 10^5queries[i] == [l_i, r_i]0 <= l_i <= r_i < s.length- All queries are distinct.
Solution
Approach: Sliding Window + Prefix Sums
First run the sliding window from Part I over the whole string. For every start i, let d[i] be the first end position j at which the substring starting at i stops satisfying the constraint (n if it never does); this is recorded when the window's left end moves past i. Also let pre[j + 1] be the running total of j - left + 1, the number of valid substrings ending at each position j.
For a query [l, r], let p = min(r + 1, d[l]). The substring [l, p - 1] is valid, so every substring inside it is valid, which gives (p - l) * (p - l + 1) / 2 substrings. For an end j in [p, r], the substring [l, j] is invalid, so the valid substrings ending at j start to the right of l, and all of them lie inside the query: there are j - left + 1 of them. Their total is pre[r + 1] - pre[p]. The answer is the sum of the two parts.
Complexity: O(n + q) time and O(n) space for a string of length n and q queries.
class Solution:
def countKConstraintSubstrings(
self, s: str, k: int, queries: List[List[int]]
) -> List[int]:
cnt = [0, 0]
i, n = 0, len(s)
d = [n] * n
pre = [0] * (n + 1)
for j, x in enumerate(map(int, s)):
cnt[x] += 1
while cnt[0] > k and cnt[1] > k:
d[i] = j
cnt[int(s[i])] -= 1
i += 1
pre[j + 1] = pre[j] + j - i + 1
ans = []
for l, r in queries:
p = min(r + 1, d[l])
a = (1 + p - l) * (p - l) // 2
b = pre[r + 1] - pre[p]
ans.append(a + b)
return ans