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
Balance Transformation: "10110" โ†’ [-1, +2, -1, -1, +2]1-10+21-11-10+2Running Balance TrackerStart: balance = 0, count[0] = 1After '1': balance = -1, result += count[-1] = 0After '0': balance = 1, result += count[1] = 0After '1': balance = 0, result += count[0] = 1 โœ“Same balance = Valid substring!๐ŸŽฏ Key Insight: When balance repeats, substring between has target ratio
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!
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
42.7K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen