KatInterview

Maximum Span with Limited Character Variety

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

Last updated

Tests ability to apply two-pointer sliding window technique with hash map tracking to efficiently find optimal substring boundaries.

Write a function that determines the length of the longest contiguous portion of a string where the number of unique characters does not exceed a given limit.

You are given:

  • text: a string consisting of lowercase English letters
  • limit: a non-negative integer representing the maximum number of distinct characters allowed

Return the length of the longest substring that contains no more than limit distinct characters.

Constraints

  • 0 ≤ len(text) ≤ 100,000
  • 0 ≤ limit ≤ 26
  • text contains only lowercase English letters a-z
  • If limit is 0, the answer is 0 (no characters allowed)
  • If text is empty, the answer is 0

Examples

Example 1

Input: max_length_with_k_chars('eceba', 2)

Output: 3

Example 2

Input: max_length_with_k_chars('aa', 1)

Output: 2

Example 3

Input: max_length_with_k_chars('aabbcc', 2)

Output: 4

Example 4

Input: max_length_with_k_chars('abracadabra', 3)

Output: 5

Hints

Hint 1

Track character frequencies using a dictionary while expanding a window

Hint 2

Use two pointers: expand the right boundary to grow the window, contract the left boundary when too many distinct characters appear

Hint 3

Remove characters from your frequency map when their count drops to zero to maintain an accurate count of distinct characters