Maximum Number of Vowels in a Substring of Given Length

Slide a window of k characters across a string and find the most vowels it ever holds.

Given a string s of lowercase English letters and an integer k, return the largest number of vowels in any substring of s of length k. The vowels are a, e, i, o and u. A substring is a run of characters that sit next to each other in s, and k is at least 1 and at most the length of s.

Example 1
Input: s = "abciiidef", k = 3
Output: 3
Explanation: the substring "iii" has 3 vowels.
Example 2
Input: s = "aeiou", k = 2
Output: 2
Explanation: every substring of length 2 has 2 vowels.
Example 3
Input: s = "cscode", k = 3
Output: 2
Explanation: the substring "ode" has 2 vowels.
Solution

The Idea

Picture a strip of card with a slot cut in it, exactly 3 letters wide, laid over the word "abciiidef". Through the slot you see one substring of length 3. Slide the card one letter at a time from the left end to the right end, and count the vowels you see at each stop. The answer is the biggest count.

For Example 1 the slot shows "abc" (1 vowel), then "bci" (1), "cii" (2), "iii" (3), "iid" (2), "ide" (2) and "def" (1). That is seven stops, and the best is 3. Counting every stop from scratch means reading all 3 letters again each time. Is that really needed, when two neighbouring stops share most of their letters?

Look at the picture below. The part of the string inside the slot is called the window, drawn as the blue frame. The small number under each letter is its position, counting from 0.

The string abciiidef with a window of 3 characters. The window cii at positions 2 to 4 holds 2 vowels. Sliding it one step right, c leaves and i enters, and the window iii holds 3 vowels.

In the top row, labelled window "cii", the frame covers positions 2 to 4 and holds 2 vowels. In the row labelled window "iii", the frame has moved one step right. Only two letters changed: c at position 2 left, and i at position 5 entered. The two i's at positions 3 and 4 stayed where they were.

So the new count follows from the old one. The c that left was not a vowel, so nothing comes off. The i that entered is a vowel, so 1 goes on, and 2 becomes 3. Each step needs a look at only two letters, however wide the window is.

Moving a window of fixed size one step at a time, and updating what it holds instead of recomputing it, is called the sliding window technique.

Solution Approach

Turning that idea into code means settling three things: how to update the count at each step, how to build the first window, and where to keep the best count.

Updating the count at each step

Why not just count the vowels of each window again? A string of length n has n - k + 1 windows, and each one takes k reads. For n = 100,000 and k = 50,000 that is about 2.5 billion reads. Updating the count takes two reads per step instead.

Which two characters change? Call the position of the window's right end i. The character entering is the one at i, and the one leaving is k places before it, at i - k. In the picture, the right end moved to 5, and 5 - 3 = 2, the position of the c that left.

Building the first window

What about the start, before the window holds k characters? While i is less than k, nothing has left yet, because there is no position i - k. So the same loop can build the first window: it adds characters as they enter and only starts removing once i reaches k. In Example 1, the window grows through "a" and "ab" to "abc" before it starts to move.

Keeping the best count

Where does the answer come from? A variable holds the best count seen so far, and it is compared with the count after every step. The counts during the growing stage, for "a" and "ab", are never bigger than the count for "abc", which contains them, so comparing them too does no harm.

Stopping early (optional)

A window of k characters holds at most k vowels. So once the count reaches k, nothing can beat it, and the method could return straight away. This helps on strings with long runs of vowels, but a string with few vowels still needs the full pass, so the code below leaves it out.

Java Solution

The method maxVowels works in these steps:

  1. First, set count, the number of vowels in the current window, and best, the largest count seen so far, both to 0.
  2. Move i, the window's right end, along the string with one loop. If s.charAt(i) is a vowel, add 1 to count, because that character enters the window. A small helper, isVowel, compares a character with the five vowels.
  3. Once i is at least k, the character at i - k has just left the window. If it is a vowel, subtract 1 from count.
  4. After both checks, update best with Math.max(best, count).
  5. When the loop ends, return best.

The main method runs the three examples, a string with no vowels, a window as long as the whole string, and a string whose only vowels are its last two characters.

Java
public class MaximumNumberOfVowelsInSubstringOfGivenLength {

    public static int maxVowels(String s, int k) {
        int count = 0;
        int best = 0;
        for (int i = 0; i < s.length(); i++) {
            if (isVowel(s.charAt(i))) {
                count++;                      // character i enters the window
            }
            if (i >= k && isVowel(s.charAt(i - k))) {
                count--;                      // character i - k leaves it
            }
            best = Math.max(best, count);
        }
        return best;
    }

    private static boolean isVowel(char c) {
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }

    public static void main(String[] args) {
        System.out.println(maxVowels("abciiidef", 3));
        System.out.println(maxVowels("aeiou", 2));
        System.out.println(maxVowels("cscode", 3));
        System.out.println(maxVowels("rhythm", 2));
        System.out.println(maxVowels("abe", 3));
        System.out.println(maxVowels("xyzxyzaa", 2));
    }
}

Running it prints:

Output
3
2
2
0
2
2

Look at the third line, 2 for "cscode" with k = 3. This is where a wrong leaving position would show. With i - k + 1 instead of i - k, the last step subtracts the o at position 3, which is still the first character of the window "ode". That version returns 1.

The fourth line is 0, because "rhythm" has no vowels and count never moves. The fifth line, 2, comes from "abe" with k = 3: the window is the whole string, so nothing ever leaves, and the a and the e give the answer. In the last line, "xyzxyzaa" with k = 2, best stays at 0 until the final two steps, when the two a's enter.

The original implementation, MaximumNumberOfVowelsInSubstringOfGivenLength.java, is on GitHub.

Complexity

The work is a single pass over the string, with a fixed amount of work at each step.

  • Time: O(n), because the window's right end i visits each of the n characters once, and each visit checks at most two characters, the one entering and the one leaving.
  • Space: O(1), because the method keeps only count, best and i, and reads the string by index with charAt without copying it.

Windows of fixed size are the first pattern in Sliding Window Basics.