KatInterview

Maximum Unique Character Window

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

Last updated

Tests sliding window technique with hash map to track character positions and find the longest contiguous segment with all distinct characters.

You are given a string s. Your task is to determine the length of the longest contiguous segment within the string where no character appears more than once.

A contiguous segment is a sequence of consecutive characters from the string. For example, in "hello", the segments "hel" and "llo" are contiguous, but "hlo" is not.

Write a function that returns the length of the longest such segment.

Constraints

  • 0 <= len(s) <= 50000
  • The string may contain English letters (both cases), digits, symbols, and spaces
  • An empty string has a longest unique segment of length 0

Examples

Example 1

Input: length_of_longest_substring('abcabcbb')

Output: 3

Example 2

Input: length_of_longest_substring('bbbbb')

Output: 1

Example 3

Input: length_of_longest_substring('pwwkew')

Output: 3

Hints

Hint 1

Think about maintaining a window of valid characters and expanding it as you scan through the string

Hint 2

Use a dictionary to remember where each character was last seen so you can quickly adjust the window when you encounter a duplicate

Hint 3

When you find a repeated character, you need to move the left boundary of your window just past the previous occurrence of that character