Problem 56
Longest Substring Without Repeating Characters
Medium · 20 pts · String, Sliding Window, Hash Table
Problem
You are given a string S. Find the length of the longest substring (a contiguous block of characters) in which no character appears twice. A sliding window solves this in O(N): extend the window to the right one character at a time, and whenever the new character is already inside the window, move the window's left edge just past the earlier copy of that character. Track the largest window size seen.
Input
A single string S of lowercase letters and digits.
Output
Print the length of the longest such substring.
Constraints
1 <= |S| <= 100000
Example input
abcabcbb
Example output
3
Explanation
In "abcabcbb", the window "abc" has no repeats. Adding the next character (another a) creates a repeat, and every substring of length 4 contains a repeated letter. So the answer is 3.