The Number of Substrings With Fixed Ratio problem gives you a binary string and two integers num1 and num2. Count substrings where the count of '0's to count of '1's equals num1:num2. This coding problem uses prefix sum with a hash map, similar to the "subarray sum divisible by k" pattern but adapted for a ratio condition.
Intuit asks this to test the transformation of a ratio condition into a linear prefix sum equation. The key: for a substring with cnt0 zeros and cnt1 ones, cnt0 * num2 == cnt1 * num1 ⟺ cnt0 * num2 - cnt1 * num1 == 0. Define diff[i] = cnt0[i] * num2 - cnt1[i] * num1 using prefix counts. Count pairs where diff[i] == diff[j]. The math, hash table, string, and prefix sum interview pattern is directly demonstrated.
Prefix difference hash map. Compute running diff = (count_of_0s * num2) - (count_of_1s * num1). Maintain a frequency map of all previous diff values. For each position i, the number of valid substrings ending here = frequency of the current diff value in the map. Increment the map for the current diff. Initialize map with {0: 1} for the empty prefix.
s="0110", num1=1, num2=2. Need cnt0/cnt1 = 1/2, i.e., diff = cnt02 - cnt11 = 0. Prefix: start with map={0:1}, diff=0.
Ratio-based substring counting always converts to "count pairs with equal prefix difference." The key transformation: cnt_a/cnt_b == p/q ⟺ cnt_a*q - cnt_b*p == 0. This reduces ratio matching to a standard prefix hash map problem. Practice similar problems: "equal '0's and '1's ratio," "subarrays with k times more '1's than '0's." The transformation technique is universally applicable to any ratio condition on counts.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Beautiful Substrings II | Hard | Solve | |
| Fraction to Recurring Decimal | Medium | Solve | |
| Integer to Roman | Medium | Solve | |
| Reconstruct Original Digits from English | Medium | Solve | |
| Roman to Integer | Easy | Solve |