LeetCode 2489: Number of Substrings With Fixed Ratio Solution
Master LeetCode problem 2489 (Number of Substrings With Fixed Ratio), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2489. Number of Substrings With Fixed Ratio
Problem Explanation
Explanation:
Given a string of digits and a fixed ratio, we need to find the number of substrings with a fixed ratio. A substring is considered valid if the ratio of the number of 0's to the number of 1's is equal to the fixed ratio.
To solve this problem, we can iterate through all possible substrings of the input string and check if the ratio of 0's to 1's in each substring matches the fixed ratio. We can keep track of the count of valid substrings and return it as the result. :
Solution Code
class Solution {
public int countSubstrings(String s, int ratio) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
int zeros = 0, ones = 0;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) == '0') {
zeros++;
} else {
ones++;
}
if (zeros != 0 && ones != 0 && zeros * ratio == ones) {
count++;
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2489 (Number of Substrings With Fixed Ratio)?
This page provides optimized solutions for LeetCode problem 2489 (Number of Substrings With Fixed Ratio) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2489 (Number of Substrings With Fixed Ratio)?
The time complexity for LeetCode 2489 (Number of Substrings With Fixed Ratio) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2489 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2489 in Java, C++, or Python.