KatInterview

Maximum Substring Length with Character Limit

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringssliding-windowhash-maptwo-pointers

Last updated

Tests sliding window technique to find the longest contiguous sequence where the number of unique characters does not exceed a threshold.

You are given a string s and a non-negative integer k. Your task is to determine the length of the longest contiguous substring where the number of unique characters does not exceed k.

Write a function that returns this maximum length as an integer.

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • 0 <= k <= 50
  • The string s consists of printable ASCII characters

Edge Case Behavior

  • When k equals 0, no valid substring exists (return 0)
  • When the string is empty, return 0
  • When the entire string contains k or fewer unique characters, the answer is the full string length

Examples

Example 1

Input: max_substring_with_k_chars('eceba', 2)

Output: 3

Example 2

Input: max_substring_with_k_chars('aa', 1)

Output: 2

Hints

Hint 1

Use two pointers to maintain a window, expanding it rightward and contracting it from the left when needed

Hint 2

Track character frequencies with a dictionary; the dictionary size tells you how many distinct characters are in your current window

Hint 3

The left pointer only moves forward, never backward, giving you linear time complexity