Longest Substring Without Repeating Characters - Problem
Given a string s, find the length of the longest substring without repeating characters.
A substring is a contiguous sequence of characters within a string. Your goal is to find the maximum possible length of a substring where all characters are unique.
Example: In the string "abcabcbb", the longest substring without repeating characters is "abc" with length 3.
Input & Output
example_1.py — Basic case with repeating characters
$
Input:
s = "abcabcbb"
›
Output:
3
💡 Note:
The answer is "abc", with the length of 3. Other valid substrings include "bca", "cab", but "abc" appears first when reading left to right.
example_2.py — All same characters
$
Input:
s = "bbbbb"
›
Output:
1
💡 Note:
The answer is "b", with the length of 1. Since all characters are the same, the longest substring without repeating characters can only be of length 1.
example_3.py — Mixed pattern
$
Input:
s = "pwwkew"
›
Output:
3
💡 Note:
The answer is "wke", with the length of 3. Note that "pwke" is a subsequence (not substring) and thus doesn't count. The longest valid substring is "wke".
Constraints
- 0 ≤ s.length ≤ 5 × 104
- s consists of English letters, digits, symbols and spaces
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty window and hash map
2
Expand
Add characters to window while they're unique
3
Contract
When duplicate found, jump left pointer efficiently
4
Continue
Keep expanding and update maximum length
Key Takeaway
🎯 Key Insight: The sliding window with hash map approach transforms an O(n³) brute force solution into an elegant O(n) algorithm by efficiently skipping past duplicate characters instead of rechecking substrings.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code