Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Sample Input: "abcabcbb"
Expected Output: 3
The answer is "abc", with a length of 3.
Constraints
0 <= s.length <= 5 * 104sconsists of English letters, digits, symbols and spaces.
How We Solve This
- Use two pointers,
startandend, to track the current substring. - Use a HashMap to remember the last index of each character.
- Move the
endpointer forward one character at a time. - If the character is already in the current substring, move the
startpointer right after its last occurrence. - Update the maximum length after processing each character.
Edge Cases to Consider
Empty String
Input:
""Output:
0The algorithm correctly returns 0 for empty inputs.
All Same Characters
Input:
"aaaa"Output:
1The window shrinks at every step, keeping max length at 1.
Spaces & Symbols
Input:
"a b!a"Output:
4Spaces and symbols are treated as unique characters.
Repeats at Start/End
Input:
"abca"Output:
3The sliding window correctly adjusts to find 'bca'.
Single Character
Input:
"z"Output:
1The minimum valid substring is handled correctly.