KatInterview

Longest Window With a Capped Number of Distinct Letters

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringssliding-windowtwo-pointershash-map

Last updated

Find the length of the longest contiguous stretch of a string using no more than k different characters, testing the sliding-window technique with a frequency map.

You are given a string text and an integer max_distinct. Look at every contiguous block of characters inside text (a substring). Among the blocks that contain no more than max_distinct different characters, find the longest one and return its length.

Characters are compared exactly as they appear in the Python string, so uppercase and lowercase letters are different characters, and each Python character (code point) counts as one character.

Edge-case rules

  • If text is empty, return 0.
  • If max_distinct is 0 or negative, no non-empty block can qualify, so return 0.
  • If max_distinct is at least the number of distinct characters in text, the whole string qualifies, so return len(text).

Task

Implement a function that returns this maximum length as an integer. Aim for a solution that runs in linear time in the length of the string.

Constraints

  • 0 <= len(text) <= 10^5
  • -10^5 <= max_distinct <= 10^5
  • text is a Python string; any characters may appear.
  • The return value is a single non-negative integer.

Examples

Example 1

Input: longest_window_max_distinct('eceba', 2)

Output: 3

Example 2

Input: longest_window_max_distinct('aa', 1)

Output: 2

Example 3

Input: longest_window_max_distinct('aabbcc', 2)

Output: 4

Example 4

Input: longest_window_max_distinct('abaccc', 2)

Output: 4

Hints

Hint 1

Checking every substring is quadratic or worse. Think about a window described by two indices, left and right, that you move through the string.

Hint 2

Keep a dictionary of how many times each character appears in the current window. The number of keys is the number of distinct characters, as long as you remove keys whose count reaches zero.

Hint 3

For each new right index, add the character, then move left forward while the window has more than max_distinct distinct characters. After that the window is valid, so compare its length with the best so far. Handle max_distinct <= 0 and empty text up front.