LeetCode 2947: Count Beautiful Substrings I Solution

Master LeetCode problem 2947 (Count Beautiful Substrings I), 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.

2947. Count Beautiful Substrings I

Problem Explanation

Explanation

To solve this problem, we can iterate through all possible substrings of the given string s. For each substring, we calculate the number of vowels and consonants. If the count of vowels and consonants are equal and their product is divisible by k, then we increment the count of beautiful substrings.

Algorithm

  1. Initialize a variable count to store the count of beautiful substrings.
  2. Iterate through all possible substrings of the given string s.
  3. For each substring, calculate the count of vowels and consonants.
  4. If the count of vowels and consonants are equal and their product is divisible by k, increment count.
  5. Return the final count as the result.

Time Complexity

The time complexity of this algorithm is O(n^2), where n is the length of the input string s.

Space Complexity

The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public int countBeautifulSubstrings(String s, int k) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 1; j <= s.length(); j++) {
                String substring = s.substring(i, j);
                int vowels = 0, consonants = 0;
                for (char c : substring.toCharArray()) {
                    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                        vowels++;
                    } else {
                        consonants++;
                    }
                }
                if (vowels == consonants && (vowels * consonants) % k == 0) {
                    count++;
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2947 (Count Beautiful Substrings I)?

This page provides optimized solutions for LeetCode problem 2947 (Count Beautiful Substrings I) 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 2947 (Count Beautiful Substrings I)?

The time complexity for LeetCode 2947 (Count Beautiful Substrings I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2947 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2947 in Java, C++, or Python.

Back to LeetCode Solutions