Number of Substrings With Fixed Ratio - Problem
Given a binary string s and two coprime integers num1 and num2, find the number of substrings where the ratio of 0's to 1's is exactly num1 : num2.
A ratio substring is a contiguous sequence where:
- Number of 0's / Number of 1's = num1 / num2
- Both counts must be positive (non-empty substring)
Examples of valid ratio substrings:
- If
num1 = 2, num2 = 3: "01011" has 2 zeros and 3 ones โ - If
num1 = 1, num2 = 1: "01" has 1 zero and 1 one โ
Your task is to count all possible such ratio substrings in the given binary string.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "10110", num1 = 1, num2 = 2
โบ
Output:
4
๐ก Note:
Valid substrings: "01" (1 zero, 1 one scaled to 1:2), "10" (1 zero, 1 one), "011" (2 zeros, 1 one = 2:1), "0110" (2 zeros, 2 ones = 1:1 scaled to 1:2)
example_2.py โ Equal Ratio
$
Input:
s = "01", num1 = 1, num2 = 1
โบ
Output:
1
๐ก Note:
Only one valid substring "01" with 1 zero and 1 one, giving ratio 1:1
example_3.py โ No Valid Substrings
$
Input:
s = "111", num1 = 1, num2 = 2
โบ
Output:
0
๐ก Note:
String contains only 1's, so no substring can have any 0's to match the 1:2 ratio
Constraints
- 1 โค s.length โค 105
- s consists only of '0' and '1'
- 1 โค num1, num2 โค 105
- num1 and num2 are coprime (gcd(num1, num2) = 1)
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with balance 0 and empty hash map
2
Process Character
Update balance: +num2 for '0', -num1 for '1'
3
Check History
Count how many times we've seen this balance before
4
Record Balance
Store current balance in hash map for future reference
Key Takeaway
๐ฏ Key Insight: The prefix sum transformation converts the ratio problem into finding equal balance points, making it solvable in O(n) time with a hash map!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code