Solving Leetcode Interviews in Seconds with AI: Count of Substrings Containing Every Vowel and K Consonants I
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3305" 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 <= 250 word consists only of lowercase English letters. 0 <= k <= word.length - 5
Explanation
Here's a breakdown of the solution:
- Sliding Window: Use a sliding window approach to iterate through all possible substrings of the input
word. The window expands until it contains all vowels at least once and exactlykconsonants. - Vowel/Consonant Counting: Maintain counts of each vowel and the total number of consonants within the current window. This allows efficient validation of whether the substring meets the problem criteria.
Window Adjustment: If the current window satisfies the conditions, increment the result. Then shrink the window from the left, updating counts accordingly, and continue checking.
Runtime Complexity: O(n), where n is the length of the input string.
- Storage Complexity: O(1), as the vowel and consonant counts are stored in a fixed-size array.
Code
def count_substrings(word: str, k: int) -> int:
"""
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.
"""
n = len(word)
count = 0
for i in range(n):
vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
consonant_count = 0
for j in range(i, n):
char = word[j]
if char in vowels:
vowels[char] += 1
elif 'a' <= char <= 'z':
consonant_count += 1
vowel_condition = all(vowels[v] > 0 for v in vowels)
if vowel_condition and consonant_count == k:
count += 1
elif consonant_count > k:
break
return count