Longest Substring Without Repeating Characters
Medium
Topics
Given a string s, find the length of the longest substring without repeating characters.
Example 1
The braced run is the longest stretch with no repeated character, length 3 (
abc). The window only ever moves forwards: on a repeat, the left edge jumps past the previous occurrence rather than restarting, so each character is visited once.Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc".
Example 2
Input: s = "bbbbb" Output: 1
Constraints
- 0 <= s.length <= 5*10^4
- s consists of English letters, digits, symbols and spaces.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Slide a window over the string keeping it free of duplicates. When the new character was already inside the window, jump the left edge to just past its previous position — that removes the duplicate in O(1).
The window only ever grows on the right and jumps forward on the left, so each character is handled once.
Approach
- Store the last index seen for each character and a
leftboundary. - For character at
right: if it was seen at index ≥left, setleft = lastSeen + 1. - Record its new index and update the best length
right - left + 1.
Walkthrough
s = "abcabcbb"
window grows to "abc" (len 3)
at index 3 (a): a seen at 0 -> left=1, window "bca"
... best stays 3 -> answer 3Complexity
- Time — O(n): each character is visited once;
leftonly moves forward. - Space — O(min(n, charset)): at most one map entry per distinct character.
Common Pitfalls
- The
seen[c] >= leftcheck matters — an old occurrence outside the window must be ignored.
Full Solution — all languages
class Solution:
def lengthOfLongestSubstring(self, s):
last = {}
start = res = 0
for i, c in enumerate(s):
if c in last and last[c] >= start:
start = last[c] + 1
last[c] = i
res = max(res, i - start + 1)
return resimport java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> last = new HashMap<>();
int start = 0, res = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (last.containsKey(c) && last.get(c) >= start) start = last.get(c) + 1;
last.put(c, i);
res = Math.max(res, i - start + 1);
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int lengthOfLongestSubstring(string s) {
unordered_map<char,int> last;
int start = 0, res = 0;
for (int i = 0; i < (int)s.size(); i++) {
char c = s[i];
if (last.count(c) && last[c] >= start) start = last[c] + 1;
last[c] = i;
res = max(res, i - start + 1);
}
return res;
}
};/**
* @param {string} s
* @return {number}
*/ var lengthOfLongestSubstring = function(s) {
const last = {};
let start = 0, res = 0;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c in last && last[c] >= start) start = last[c] + 1;
last[c] = i;
res = Math.max(res, i - start + 1);
}
return res;
};