Magicsheet logo

Count of Substrings Containing Every Vowel and K Consonants II

Medium
12.5%
Updated 8/1/2025

Count of Substrings Containing Every Vowel and K Consonants II

What is this problem about?

The "Count of Substrings Containing Every Vowel and K Consonants II interview question" is a medium-to-hard string manipulation problem. You are given a string and a target integer k. You need to find the number of substrings that satisfy two specific conditions:

  1. They contain all five vowels ('a', 'e', 'i', 'o', 'u') at least once.
  2. They contain exactly k consonants. This problem scales the complexity of basic vowel-counting by requiring an exact count of consonants while maintaining the full vowel set.

Why is this asked in interviews?

Amazon and Bloomberg ask the "Count of Substrings Containing Every Vowel and K Consonants II coding problem" to test a candidate's mastery of the Sliding Window technique. It requires managing multiple counts (vowel frequencies and a consonant counter) simultaneously. It evaluates the ability to solve "Exactly K" problems by transforming them into "At Least K" or "At Most K" sub-problems, which is a key algorithmic optimization.

Algorithmic pattern used

This problem follows the Sliding Window and Hash Table pattern.

  1. The "Exactly K" Trick: The number of substrings with exactly kk consonants is equal to (substrings with at least kk consonants) minus (substrings with at least k+1k+1 consonants).
  2. Window Management: Maintain a window [left,right][left, right]. Expand the right pointer and update frequencies.
  3. Vowel Check: Use a hash map or array to track the counts of the five vowels. A window is "vowel-complete" if the map has 5 entries.
  4. Shrink Window: If the current window meets the "all vowels" and "at least kk consonants" condition, then all substrings starting at left and ending beyond the current right are potentially valid.

Example explanation

Suppose string is "aeiouxx" and k=2k=2.

  • The window "aeiouxx" contains all 5 vowels and exactly 2 consonants ('x', 'x').
  • If we had "aeiouxxx" and k=2k=2:
    • Substrings like "aeiouxx" are valid.
    • Substrings like "aeiouxxx" are not (3 consonants). The sliding window helps us find the boundaries where the consonant count changes from kk to k+1k+1.

Common mistakes candidates make

  • Recalculating everything: Using a brute-force approach to check every substring, which is O(N3)O(N^3) or O(N2)O(N^2).
  • Ignoring non-vowel characters: Not correctly identifying consonants (any character that isn't 'a', 'e', 'i', 'o', 'u').
  • Off-by-one errors: Mismanaging the pointers when trying to find the exact count of consonants.

Interview preparation tip

For any problem that asks for "exactly K items," always consider if it's easier to calculate "At most K" or "At least K." This "Sliding Window interview pattern" transformation is one of the most powerful tools for solving string and array challenges efficiently.

Similar Questions