Number of Substrings With Fixed Ratio - Problem

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 = 2 and num2 = 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 x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.

Input & Output

Example 1 — Basic Valid Substring
$ Input: s = "0110", num1 = 1, num2 = 2
Output: 4
💡 Note: Substrings with 1:2 ratio (zeros:ones): "01" (1 zero, 2 ones is invalid), "0110" (2 zeros, 2 ones = 1:1 ≠ 1:2), but "01", "10", "011", "110" need checking. Actually valid ones are those where zeros*2 = ones*1.
Example 2 — Single Character
$ Input: s = "0", num1 = 1, num2 = 1
Output: 0
💡 Note: Single '0' has ratio 1:0, but we need 1:1 ratio, so no valid substrings.
Example 3 — Multiple Valid Substrings
$ Input: s = "01011", num1 = 2, num2 = 3
Output: 1
💡 Note: Only "01011" itself has 2 zeros and 3 ones, giving exact 2:3 ratio.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of '0' and '1'
  • 1 ≤ num1, num2 ≤ 100
  • gcd(num1, num2) = 1

Visualization

Tap to expand
Number of Substrings With Fixed RatioInput String:01011Target Ratio: 2:3 (zeros:ones)Check All SubstringsCount zeros and ones in eachVerify ratio matches 2:3Output: Number of valid substrings1
Understanding the Visualization
1
Input
Binary string and target ratio num1:num2
2
Process
Check each substring for exact ratio match
3
Output
Count of valid ratio substrings
Key Takeaway
🎯 Key Insight: Transform ratio checking into prefix sum difference tracking for O(n) efficiency
Asked in
Google 25 Meta 18 Amazon 15
28.5K Views
Medium Frequency
~25 min Avg. Time
856 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