KatInterview

Maximum Unique Character Window Length

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

Last updated

Tests sliding window technique with hash map indexing to efficiently find the longest substring with all distinct characters.

Write a function that finds the length of the longest contiguous substring within a given string where every character appears exactly once.

You are given a string s that may include any printable characters: lowercase and uppercase letters, digits, punctuation, and whitespace.

Your task is to return an integer representing the maximum length of any substring in which no character is repeated.

Constraints

  • 0 ≤ len(s) ≤ 100,000
  • The string may be empty
  • All characters are treated as distinct entities (case-sensitive, spaces count as characters)
  • You must solve this in better than O(n²) time complexity

Notes

  • A substring is a contiguous sequence of characters, not a subsequence
  • If the string is empty, return 0
  • Only the length is required, not the substring itself

Examples

Example 1

Input: max_unique_substring_length('abcabcbb')

Output: 3

Example 2

Input: max_unique_substring_length('bbbbb')

Output: 1

Example 3

Input: max_unique_substring_length('pwwkew')

Output: 3

Hints

Hint 1

Use a sliding window approach where you maintain a valid window of unique characters and expand it character by character.

Hint 2

Track the most recent position of each character you've seen using a dictionary.

Hint 3

When you encounter a duplicate character, you need to move the window start forward—but only if the previous occurrence is actually inside your current window.