Number of Substrings With Fixed Ratio Problem
Description
LeetCode Problem 2489.
You are given a binary string s, and two integers num1 and num2. num1 and num2 are coprime numbers.
A ratio substring is a substring of s where the ratio between the number of 0's and the number of 1's in the substring is exactly num1 : num2.
- For example, if
num1 = 2andnum2 = 3, then"01011"and"1110000111"are ratio substrings, while"11000"is not.
Return the number of non-empty ratio substrings of s.
Note that:
- A substring is a contiguous sequence of characters within a string.
- Two values
xandyare coprime ifgcd(x, y) == 1wheregcd(x, y)is the greatest common divisor ofxandy.
Example 1:
Input: s = "0110011", num1 = 1, num2 = 2
Output: 4
Explanation: There exist 4 non-empty ratio substrings.
- The substring s[0..2]: "0110011". It contains one 0 and two 1's. The ratio is 1 : 2.
- The substring s[1..4]: "0110011". It contains one 0 and two 1's. The ratio is 1 : 2.
- The substring s[4..6]: "0110011". It contains one 0 and two 1's. The ratio is 1 : 2.
- The substring s[1..6]: "0110011". It contains two 0's and four 1's. The ratio is 2 : 4 == 1 : 2.
It can be shown that there are no more ratio substrings.
Example 2:
Input: s = "10101", num1 = 3, num2 = 1
Output: 0
Explanation: There is no ratio substrings of s. We return 0.
Constraints:
1 <= s.length <= 10^51 <= num1, num2 <= s.lengthnum1andnum2are coprime integers.
Solution
Approach: Prefix balance and counting
Let zero[i] and one[i] be the number of 0s and 1s in the first i characters. A substring from i to j has zeros to ones in ratio num1 : num2 when (zero[j] - zero[i]) * num2 = (one[j] - one[i]) * num1. Rearranging, this is one[j] * num1 - zero[j] * num2 = one[i] * num1 - zero[i] * num2, so two prefixes bound a good substring exactly when they have the same key.
So for each prefix compute the key x = one * num1 - zero * num2, add the number of earlier prefixes with the same key to the answer, then record this prefix. The empty prefix has key 0, so the map starts with {0: 1}.
Complexity: time O(n); space O(n).
class Solution:
def fixedRatio(self, s: str, num1: int, num2: int) -> int:
n0 = n1 = 0
ans = 0
cnt = Counter({0: 1})
for c in s:
n0 += c == '0'
n1 += c == '1'
x = n1 * num1 - n0 * num2
ans += cnt[x]
cnt[x] += 1
return ans