MediumNo. 2489LeetCode Premium
Number of Substrings With Fixed Ratio — LeetCode 2489 Python Solution
- Pattern
- Prefix Sum
- Topics
- Hash Table, Math, String, Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 2947 | Count Beautiful Substrings I | Medium |
| 0012 | Integer to Roman | Medium |
| 0013 | Roman to Integer | Easy |
| 0166 | Fraction to Recurring Decimal | Medium |
| 0423 | Reconstruct Original Digits from English | Medium |
| 0523 | Continuous Subarray Sum | Medium |
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.