KatInterview

Maximum Distinct Character Window

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

Last updated

Tests sliding window technique with hash maps to find the longest contiguous span of non-repeating characters in a string.

You are given a string s. Your task is to find the length of the longest contiguous substring where all characters are distinct (no character appears more than once).

A substring is a consecutive sequence of characters within the string. For instance, "abc" is a substring of "abcabcbb", but "ac" is not (it skips "b").

Return an integer representing the length of the longest such substring.

Constraints:

  • 0 <= len(s) <= 50,000
  • s consists of any printable characters including letters, digits, spaces, and symbols
  • Characters are case-sensitive: 'A' and 'a' are treated as different characters
  • If the string is empty, return 0

Examples

Example 1

Input: max_distinct_window('abcabcbb')

Output: 3

Example 2

Input: max_distinct_window('bbbbb')

Output: 1

Example 3

Input: max_distinct_window('pwwkew')

Output: 3

Example 4

Input: max_distinct_window('')

Output: 0

Hints

Hint 1

Consider maintaining a window that expands and contracts as you scan through the string from left to right.

Hint 2

Use a dictionary to remember where each character last appeared, so you can quickly detect when a duplicate enters your current window.

Hint 3

When you encounter a character that already exists in your current window, you need to shrink the window from the left, but be careful not to move the left boundary backward.