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".

Visualization

Tap to expand
Sliding Window Algorithm VisualizationInput: "abcabcbb"a0b1c2a3b4c5b6b7Current Window: "abc" (length=3)LEFTRIGHTAlgorithm Steps1. Window [0,2]: "abc" - all unique โœ“ (max_len = 3)2. At index 3: found 'a' again3. Jump LEFT pointer: left = map['a'] + 1 = 14. Update map: map['a'] = 35. New window [1,3]: "bca" (length = 3)6. Continue until end of string...Key InsightInstead of moving LEFT pointer one by one,we JUMP it past the duplicate character.This reduces time complexity from O(nยฒ) to O(n)!Final Result: Maximum Length = 3Time: O(n) | Space: O(min(m,n)) where m = character set size
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.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the string with constant time hash map operations

n
2n
โœ“ Linear Growth
Space Complexity
O(min(m,n))

Hash map stores at most min(charset_size, string_length) characters

n
2n
โšก Linearithmic Space

Constraints

  • 0 โ‰ค s.length โ‰ค 5 ร— 104
  • s consists of English letters, digits, symbols and spaces
Asked in
Amazon 127 Google 95 Microsoft 73 Meta 68 Apple 45 Bloomberg 42
89.3K Views
Very High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen