Longest Substring Without Repeating Characters
Medium
Sliding WindowStringHash Map
Problem
Given a string s, return the length of the longest substring with all distinct characters.
Example 1
Input: s = "abcabcbb"
Output: 3
Explain: "abc"
Example 2
Input: s = "bbbbb"
Output: 1
Example 3
Input: s = "pwwkew"
Output: 3
Explain: "wke"
Constraints
- 0 ≤ s.length ≤ 5·10⁴
- s may contain any ASCII char
Approach — Sliding Window
This is a Sliding Window problem. The idea: keep a moving window over the sequence, expanding and shrinking it while tracking the answer in a single pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
class Solution:
def lengthOfLongestSubstring(self, s):
seen = {}
start = best = 0
for i, c in enumerate(s):
if c in seen and seen[c] >= start:
start = seen[c] + 1
seen[c] = i
best = max(best, i - start + 1)
return best
Java
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastSeen = new HashMap<>();
int maxLength = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
if (lastSeen.containsKey(ch) && lastSeen.get(ch) >= left) {
left = lastSeen.get(ch) + 1;
}
lastSeen.put(ch, right);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Longest Substring Without Repeating Characters interactively → ← All solutions