Problem 332950 · medium · Level 03 Linear Management & Searching

Tasting Menu with k Flavours

sliding window · variable-size window · hash map

A tasting counter serves dishes in order; menu is a lowercase string where each letter is a flavour. A guest can handle at most k different flavours in one sitting. Return the length of the longest contiguous stretch of dishes containing at most k distinct flavours.

Examples

Input:  menu = "abacbcc", k = 2
Output: 4
Explanation: "cbcc" uses only flavours c and b.

Input:  menu = "zzz", k = 1
Output: 3

Input:  menu = "abc", k = 0
Output: 0

Constraints

  • 0 <= len(menu) <= 10**5, 0 <= k <= 26
  • menu consists of lowercase English letters.
  • Target complexity: O(n) time; building a set for every substring is far too slow for the largest tests.

Goals

  • Maintain a frequency map and the number of distinct keys in the window
  • Shrink the window when the distinct count exceeds the limit
Starting Python…