Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count of Substrings Containing Every Vowel and K Consonants II

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3306" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given a string word and a non-negative integer k. Return the total number of substrings of word that contain every vowel ('a', 'e', 'i', 'o', and 'u') at least once and exactly k consonants. Example 1: Input: word = "aeioqq", k = 1 Output: 0 Explanation: There is no substring with every vowel. Example 2: Input: word = "aeiou", k = 0 Output: 1 Explanation: The only substring with every vowel and zero consonants is word[0..4], which is "aeiou". Example 3: Input: word = "ieaouqqieaouqq", k = 1 Output: 3 Explanation: The substrings with every vowel and one consonant are: word[0..5], which is "ieaouq". word[6..11], which is "qieaou". word[7..12], which is "ieaouq". Constraints: 5 <= word.length <= 2 * 105 word consists only of lowercase English letters. 0 <= k <= word.length - 5

Explanation

Here's the breakdown of the approach, complexity, and Python code for solving the problem:

  • High-Level Approach:

    • Iterate through all possible substrings of the given word.
    • For each substring, check if it contains all vowels at least once and exactly k consonants.
    • Maintain a count of substrings that satisfy both conditions.
  • Complexity:

    • Runtime: O(n^3) - due to nested loops for substring generation O(n^2), and vowel/consonant counting within each substring O(n).
    • Storage: O(1) - constant extra space is used.

Code

    def count_substrings(word, k):
    """
    Counts the number of substrings of word that contain every vowel
    at least once and exactly k consonants.

    Args:
        word: The input string.
        k: The target number of consonants.

    Returns:
        The number of substrings that satisfy the conditions.
    """

    n = len(word)
    count = 0

    for i in range(n):
        for j in range(i, n):
            substring = word[i:j+1]
            vowel_counts = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
            consonant_count = 0

            for char in substring:
                if char in vowel_counts:
                    vowel_counts[char] += 1
                else:
                    consonant_count += 1

            all_vowels_present = all(vowel_counts[vowel] > 0 for vowel in vowel_counts)

            if all_vowels_present and consonant_count == k:
                count += 1

    return count

More from this blog

C

Chatmagic blog

2894 posts