Given a lowercase stringsand a positive integerk, return the length of the shortest substring containing at leastkvowels. Return0if no such substring exists.
Move right across the string and count the vowels in the current window. Once the count reaches k, the window is valid, but characters at the left edge may still be unnecessary. Record the current length, then move left forward while the window remains valid. If removing the leftmost character leaves at least k vowels, the next loop iteration records a shorter candidate. Once the vowel count falls below k, shrinking stops. The next iteration expands the window by moving right.
The condition requires a while loop because removing a consonant does not change the vowel count. Several characters may leave before the window becomes invalid. For a fixed right, the loop moves left until removing one more character makes the window invalid. The last valid length recorded is therefore the shortest valid window ending at right. Comparing those lengths across all right endpoints gives the shortest valid window in the string.
Find the shortest window containing two vowels
- vowel_count
- 0
- best_length
- not found
- status
- invalid
If no window ever reaches k vowels, best_length remains infinity and the function returns 0.
right visits each character once, and left removes each character at most once. The nested loop does not make the algorithm quadratic because both pointers move only forward. The vowel set has five entries, and the remaining state uses a fixed number of variables.