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: 2
💡 Note: Substrings with 1:2 ratio (zeros:ones) where ones*1 = zeros*2: "011" (1 zero, 2 ones: 2*1 = 1*2) and "110" (1 zero, 2 ones: 2*1 = 1*2). Total: 2 valid substrings.
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 Ratio INPUT Binary String s: 0 idx 0 1 idx 1 1 idx 2 0 idx 3 Parameters: num1 = 1 num2 = 2 Target Ratio (0s : 1s): 1 : 2 Find substrings where count(0)/count(1) = 1/2 (num1, num2 are coprime) ALGORITHM (Hash) 1 Transform Problem cnt0*num2 - cnt1*num1 = k Track diff = num2*c0 - num1*c1 2 Hash Map Setup map[diff] = count of prefix Initialize: map[0] = 1 3 Iterate String If s[i]='0': diff += num2 If s[i]='1': diff -= num1 4 Count Matches result += map[diff] map[diff]++ Execution Trace: i s[i] diff cnt res 0 0 2 0 0 1 1 1 0 0 2 1 0 1 1 3 0 2 1 2 FINAL RESULT Output: 4 Valid Ratio Substrings: "011" (idx 0-2) 0:1 = 1:2 "110" (idx 1-3) 0:1 = 1:2 "0110" (idx 0-3) 0:1 = 2:2=1:1 "011" & "110" Both valid OK - Count = 4 Key Insight: Transform ratio condition cnt0:cnt1 = num1:num2 into cnt0*num2 - cnt1*num1 = 0. Use prefix sum with hash map: for each position, compute diff = num2*zeros - num1*ones. Same diff values indicate valid substrings between those positions. Time: O(n), Space: O(n). TutorialsPoint - Number of Substrings With Fixed Ratio | Hash Approach
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