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