Sliding Window Technique

Great problem to describe the sliding window technique: https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/

1456. Maximum Number of Vowels in a Substring of Given Length
Medium

Given a string s and an integer k.

Return the maximum number of vowel letters in any substring of s with length k.

Vowel letters in English are (a, e, i, o, u).

 

Example 1:

Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.

Example 2:

Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.

Example 3:

Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.

Example 4:

Input: s = "rhythms", k = 4
Output: 0
Explanation: We can see that s doesn't have any vowel letters.

Example 5:

Input: s = "tryhard", k = 4
Output: 1

 

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.
  • 1 <= k <= s.length
Accepted
8,297
Submissions
16,907

In general such technique yields to linear execution time. Iterate thru your data linearly using an index such "i". While i is within your window "k", do the normal processing. As you go beyond k, "un-process" the beginning of the window, which will be at position i-k. That's it. Code is below, cheers, ACC.


public class Solution
{
    public int MaxVowels(string s, int k)
    {
        if (string.IsNullOrEmpty(s) || k <= 0 || k > s.Length) return 0;

        int max = 0;
        int current = 0;

        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') current++;
            if (i >= k)
            {
                if (s[i - k] == 'a' || s[i - k] == 'e' || s[i - k] == 'i' || s[i - k] == 'o' || s[i - k] == 'u') current--;
            }
            max = Math.Max(max, current);
        }

        return max;
    }
}

Comments

Popular posts from this blog

Golang vs. C#: performance characteristics (simple case study)

Claude vs ChatGPT: A Coder's Perspective on LLM Performance

ProjectEuler Problem 719 (some hints, but no spoilers)