Number of Substrings With Fixed Ratio — LeetCode 2489 Python Solution

MediumLeetCode PremiumHash TableMathStringPrefix Sum
Problem
#2489
Pattern
Prefix Sum
Reading time
3 min

The problem

You are given a binary string s, and two integers num1 and num2. num1 and num2 are coprime numbers.

Example

Input
s = "0110011", num1 = 1, num2 = 2
Output
4
Explanation
There exist 4 non-empty ratio substrings.

Python solution

Python
class Solution:
    def fixedRatio(self, s: str, num1: int, num2: int) -> int:
        n0 = n1 = 0
        ans = 0
        cnt = Counter({0: 1})
        for c in s:
            n0 += c == '0'
            n1 += c == '1'
            x = n1 * num1 - n0 * num2
            ans += cnt[x]
            cnt[x] += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2489. Number of Substrings With Fixed Ratio is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2489. Number of Substrings With Fixed Ratio?
LeetCode 2489. Number of Substrings With Fixed Ratio is rated Medium on LeetCode.
What is the time complexity of LeetCode 2489. Number of Substrings With Fixed Ratio?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2489. Number of Substrings With Fixed Ratio?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2489. Number of Substrings With Fixed Ratio cover?
LeetCode 2489. Number of Substrings With Fixed Ratio is tagged Hash Table, Math, String and Prefix Sum on LeetCode.
Is LeetCode 2489. Number of Substrings With Fixed Ratio a premium problem?
Yes. LeetCode 2489. Number of Substrings With Fixed Ratio is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview