Longest Substring Without Repeating Characters
Medium · Sliding window
Jump to codeReturn the length of the longest contiguous substring whose characters are all distinct.
Examples
Example 1
s = "abcabcbb"
Output: 3
Example 2
s = "bbbbb"
Output: 1
Constraints
- 0 <= s.length <= 1000
- s may consist of printable ASCII characters.
Need a hint?
When a duplicate arrives, jump past its last occurrence.
Asked in real interviews
Candidates reported versions of Longest Substring Without Repeating Characters from these company interviews. Some company questions are locked and open with Premium or XP.
- Solve non-repeating show substringNetflix
- Find longest substring without repeating charactersTikTok
- Find longest substring without repeating charactersMicrosoft
Solution approach
Keep a window start and a map from character to most recent index. For each character at right, set start to the larger of its current value and last occurrence + 1. Record the new occurrence and maximize right − start + 1. The maximum prevents moving the start backward.
Complexity
O(n) expected time and O(min(n, alphabet size)) space.
Python reference solution
def lengthOfLongestSubstring(s):
latest = {}
left = best = 0
for right, char in enumerate(s):
left = max(left, latest.get(char, -1) + 1)
latest[char] = right
best = max(best, right - left + 1)
return best
JavaScript solution
function lengthOfLongestSubstring(s) {
const latest = new Map();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
if (latest.has(s[right])) left = Math.max(left, latest.get(s[right]) + 1);
latest.set(s[right], right);
best = Math.max(best, right - left + 1);
}
return best;
}
Java solution
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> latest = new HashMap<>();
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
left = Math.max(left, latest.getOrDefault(c, -1) + 1);
latest.put(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
array<int, 256> latest;
latest.fill(-1);
int left = 0, best = 0;
for (int right = 0; right < (int)s.size(); right++) {
unsigned char c = s[right];
left = max(left, latest[c] + 1);
latest[c] = right;
best = max(best, right - left + 1);
}
return best;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "abcabcbb" ]
3
[ "bbbbb" ]
1
[ "pwwkew" ]
3
[ "" ]
0
[ "dvdf" ]
3
Drafts are saved per language in this browser when storage is available.