21. Longest Substring Without Repeating Characters
Find the longest continuous stretch of the string in which no character unit occurs more than once. Return its length; you do not need to return the substring itself.
A substring cannot skip characters: a subsequence is not sufficient. This course compares UTF-16 code units, so non-ASCII text follows the explicit character-counting rules below.
Example 1
Input
"abcabcbb"
Output
3
Explanation: The contiguous substring "abc" has three different characters. "bca" and "cab" are also valid length-three answers. Any length-four window in this input repeats a character, so the maximum length is 3; return the number, not the substring.
Example 2
Input
"abba"
Output
2
Explanation: The substrings "ab" and "ba" each have length 2 with no repeated character. Every longer contiguous candidate contains a repeated character, so the answer is 2.
Example 3
Input
"pwwkew"
Output
3
Explanation: The contiguous substring "wke" has three different characters, as does "kew". "pwke" is not a valid length-four answer because its letters are not consecutive in the original string: obtaining it requires skipping a character.
Constraints
0 <= s.length <= 105- Length and character comparisons use UTF-16 code units.
Hints
Hint 1
Maintain a valid interval rather than restarting each suffix.
Hint 2
Where was the newly appended char last seen?
Hint 3
Jump left past that index only if it is inside the current window.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
A stale occurrence must not move left backward
"abba"
2