LeetCode Entry

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

5.05.2023 medium 2023 kotlin

we can use Set to check if it is a vowel

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


fun maxVowels(s: String, k: Int): Int {
    val vowels = setOf('a', 'e', 'i', 'o', 'u')
    var count = 0
    var max = 0
    for (i in 0..s.lastIndex) {
        if (s[i] in vowels) count++
        if (i >= k && s[i - k] in vowels) count--
        if (count > max) max = count
    }
    return max
}

blog post substack

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/203

Intuition

Count vowels, increasing them on the right border and decreasing on the left of the sliding window.

Approach

  • we can use Set to check if it is a vowel
  • look at a[i - k] to detect if we must start move left border from i == k

    Complexity

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)