Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Vowel Substrings of a String

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2062" 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

A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it. Given a string word, return the number of vowel substrings in word. Example 1: Input: word = "aeiouu" Output: 2 Explanation: The vowel substrings of word are as follows (underlined): - "aeiouu" - "aeiouu" Example 2: Input: word = "unicornarihan" Output: 0 Explanation: Not all 5 vowels are present, so there are no vowel substrings. Example 3: Input: word = "cuaieuouac" Output: 7 Explanation: The vowel substrings of word are as follows (underlined): - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" - "cuaieuouac" Constraints: 1 <= word.length <= 100 word consists of lowercase English letters only.

Explanation

Here's a solution to the problem, focusing on efficiency:

  • Sliding Window: Iterate through all possible start positions of substrings. For each start position, expand the substring (window) to the right.
  • Vowel Tracking: Use a set to keep track of the vowels present in the current substring.
  • Early Exit: If a non-vowel character is encountered, or all five vowels are not present after expansion, move on to the next start position.

  • Runtime Complexity: O(n^2), Storage Complexity: O(1) - due to the fixed size of the vowel set.

Code

    def count_vowel_substrings(word: str) -> int:
    """
    Counts the number of vowel substrings in a given string.

    Args:
        word: The input string.

    Returns:
        The number of vowel substrings in the string.
    """

    count = 0
    n = len(word)

    for i in range(n):
        for j in range(i, n):
            substring = word[i:j+1]
            vowels = set()
            is_vowel_substring = True

            for char in substring:
                if char in 'aeiou':
                    vowels.add(char)
                else:
                    is_vowel_substring = False
                    break

            if is_vowel_substring and len(vowels) == 5:
                count += 1

    return count

More from this blog

C

Chatmagic blog

2894 posts