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
Longest Substring Without Repeating Characters INPUT String s = "abcabcbb" a 0 b 1 c 2 a 3 b 4 c 5 b 6 b 7 Hash Map Structure Char Index 'a' 0 'b' 1 'c' 2 Input Values s = "abcabcbb" length = 8 ALGORITHM STEPS 1 Initialize HashMap, left=0, maxLen=0 2 Slide Window For each char at index i 3 Check Duplicate If char in map, move left 4 Update Max maxLen = max(maxLen, i-left+1) Window Example: "abc" a b c a b left right Window length = 3 (max found) All chars unique: a, b, c FINAL RESULT Longest substring found: a b c "abc" at indices 0-2 OUTPUT 3 OK - Maximum length found! Other length-3 substrings: "bca" (idx 1-3) "cab" (idx 2-4) "abc" (idx 3-5) Key Insight: The Hash Map stores each character's most recent index, enabling O(1) duplicate detection. When a duplicate is found, we jump the left pointer past the previous occurrence, avoiding the need to shrink the window one character at a time. Time: O(n), Space: O(min(m,n)). TutorialsPoint - Longest Substring Without Repeating Characters | Hash Map Approach
Asked in
Amazon 127 Google 95 Microsoft 73 Meta 68 Apple 45 Bloomberg 42
89.4K 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