#3305

Count of Substrings Containing Every Vowel and K Consonants I

Medium
Hash TableStringSliding WindowHash MapSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a sliding window technique to efficiently count the valid substrings. By maintaining a window that expands and contracts, we can check for the required vowels and consonants without generating all substrings explicitly.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a hash map to count vowels and a variable for consonants.
  2. 2Step 2: Use two pointers (left and right) to represent the current window in the string.
  3. 3Step 3: Expand the right pointer to include more characters until all vowels are found.
  4. 4Step 4: Once all vowels are found, check if the consonants in the window equal k.
  5. 5Step 5: If they do, count valid substrings by moving the left pointer to find new valid substrings.
  6. 6Step 6: Repeat until the right pointer reaches the end of the string.
solution.py27 lines
1# Full working Python code
2
3def countSubstrings(word, k):
4    vowels = set('aeiou')
5    vowel_count = {v: 0 for v in vowels}
6    left = 0
7    consonant_count = 0
8    count = 0
9    for right in range(len(word)):
10        if word[right] in vowels:
11            vowel_count[word[right]] += 1
12        elif word[right].isalpha():
13            consonant_count += 1
14        while all(vowel_count[v] > 0 for v in vowels) and consonant_count > k:
15            if word[left] in vowels:
16                vowel_count[word[left]] -= 1
17            elif word[left].isalpha():
18                consonant_count -= 1
19            left += 1
20        if all(vowel_count[v] > 0 for v in vowels) and consonant_count == k:
21            count += left + 1
22    return count
23
24# Example usage
25print(countSubstrings('aeioqq', 1))  # Output: 0
26print(countSubstrings('aeiou', 0))    # Output: 1
27print(countSubstrings('ieaouqqieaouqq', 1))  # Output: 3

Complexity note: The time complexity is O(n) because we only traverse the string once with two pointers. The space complexity is O(1) since we only use a fixed amount of space for the vowel counts.

  • 1Using a sliding window can significantly reduce the number of checks needed compared to brute force.
  • 2Tracking counts of characters with a hash map allows for quick checks of conditions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.