Published
Longest Substring Without Repeating Characters (LeetCode 3)
Brute force, the O(n · m) middle step, and two O(n) sliding window solutions, with a traced dry run, the bug that fails on 'abba', and Python, Java and Go code tested against brute force.
Given a string s, return the length of the longest substring in which no character appears twice. Substring means contiguous: in "pwwkew" the answer is 3 ("wke"), and "pwke" doesn’t count because it skips a character.
LeetCode’s constraints: 0 ≤ s.length ≤ 5 * 10^4, and s holds English letters, digits, symbols and spaces. Two things follow from that. The empty string is a valid input (answer 0), and a space is a character like any other (" " → 1). It also means at most 95 distinct printable characters can appear, which matters more than people expect when you look at the “slow” solution below.
| Input | Output | Longest substring |
|---|---|---|
"abcabcbb" | 3 | "abc" |
"bbbbb" | 1 | "b" |
"pwwkew" | 3 | "wke" |
"" | 0 | (none) |
"abba" | 2 | "ab" or "ba" |
Keep "abba" in your head. It’s the input that breaks the most common wrong answer, and you’ll see why in the dry run.
Brute force: check every substring
Generate every s[i..j], put it in a set, and keep it if the set is as long as the substring.
def brute_force(s):
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
if len(set(s[i:j + 1])) == j - i + 1:
best = max(best, j - i + 1)
return best
There are about n²/2 substrings and building each set costs up to n, so this is O(n³). When I ran it, a random 2,000-character string took 5.85 seconds in Python. At the full 50,000 characters it would never finish. It’s still worth writing, because it’s the reference you test the fast version against.
Better: grow from each start, stop at the first repeat
Once s[i..j] contains a repeat, every longer substring starting at i does too, so there’s no point checking them. Grow from each start with a set and break as soon as you hit a character you’ve seen.
def extend_from_each_start(s):
best = 0
for i in range(len(s)):
seen = set()
for j in range(i, len(s)):
if s[j] in seen:
break
seen.add(s[j])
best = max(best, len(seen))
return best
Textbooks call this O(n²), and on an unbounded alphabet it is. But the inner loop can’t run more than m + 1 times, where m is the number of distinct characters, so it’s really O(n · m). With LeetCode’s ~95 printable characters this passes: 40 ms on a random 50,000-character string, 237 ms on the worst case I could build (the 95 characters repeated in a cycle, so every inner loop runs about 95 steps).
So why not stop here? Because an interviewer asking this question wants to see the window, and because the bound collapses on a real alphabet. Feed it Unicode text with thousands of distinct characters and you’re back to quadratic. Mention the O(n · m) observation, though. It shows you read the constraints.
Optimal: a sliding window
Notice how much work the previous version throws away. After finding "abc" from start 0, it restarts from index 1 and re-discovers "bc". A sliding window keeps that work: maintain a range s[left..right] with no repeats, move right one step at a time, and when the new character is already inside, move left forward until it isn’t.
Version 1: shrink with a set
def window_with_set(s):
seen, left, best = set(), 0, 0
for right, ch in enumerate(s):
while ch in seen: # shrink until ch is no longer inside
seen.remove(s[left])
left += 1
seen.add(ch)
best = max(best, right - left + 1)
return best
Each character is added once and removed at most once, so the total work is at most 2n steps: O(n), even with a while inside a for. This is the version I’d write first in an interview. It follows the generic “longest valid window” template exactly, so it’s hard to get wrong.
Version 2: jump left using the last index
Instead of removing characters one by one, remember where each character was last seen. When ch repeats inside the window, the new window has to start just after the previous copy, so jump straight there.
def window_with_last_index(s):
last, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left: # the old copy is inside the window
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return best
This is exactly n steps. In practice the difference is small: on 50,000 random characters version 1 took 7.5 ms and version 2 took 4.5 ms. Pick whichever you can explain without hesitating.
Dry run on "tmmzuxt"
Expected answer: 5 ("mzuxt"). This trace is the real output of trace.py from the repo, with version 2.
| right | ch | last[ch] before | left | window | best |
|---|---|---|---|---|---|
| 0 | t | none | 0 | t | 1 |
| 1 | m | none | 0 | tm | 2 |
| 2 | m | 1 | 2 | m | 2 |
| 3 | z | none | 2 | mz | 2 |
| 4 | u | none | 2 | mzu | 3 |
| 5 | x | none | 2 | mzux | 4 |
| 6 | t | 0 | 2 | mzuxt | 5 |
Look at step 6. We have seen t before, at index 0. But left is already 2, so that old t isn’t in the window any more and left stays where it is. That’s the whole point of the last[ch] >= left check.
The bug almost everyone writes first
Drop the >= left check and the code still passes the three LeetCode examples:
def buggy_no_left_check(s):
last, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in last: # BUG: the old copy may be outside the window
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return best
On "abba", the second b correctly moves left to 2. Then the final a finds last['a'] = 0 and moves left back to 1, so the window becomes "bba" and the function returns 3. On "tmmzuxt" it returns 6. I ran it against brute force on 3,000 random strings over the alphabet abcd, and it was wrong on 1,175 of them. The correct versions were wrong on 0.
left = max(left, last[ch] + 1) is an equivalent fix. Same idea: left must never move backwards.
Tested code: Python, Java and Go
All three print real output from running them. The full files, including the stress test and timing harness, are in course-code/problems/longest-substring-without-repeating-characters/ in the site’s GitHub repo.
Python (with a brute-force stress test)
The test driver for the functions above:
tests = ["abcabcbb", "bbbbb", "pwwkew", "", " ", "abba", "dvdf", "tmmzuxt"]
for s in tests:
print(f"{s!r:12} brute={brute_force(s)} extend={extend_from_each_start(s)} "
f"set={window_with_set(s)} last={window_with_last_index(s)} "
f"buggy={buggy_no_left_check(s)} substring={longest_substring(s)!r}")
'abcabcbb' brute=3 extend=3 set=3 last=3 buggy=3 substring='abc'
'bbbbb' brute=1 extend=1 set=1 last=1 buggy=1 substring='b'
'pwwkew' brute=3 extend=3 set=3 last=3 buggy=3 substring='wke'
'' brute=0 extend=0 set=0 last=0 buggy=0 substring=''
' ' brute=1 extend=1 set=1 last=1 buggy=1 substring=' '
'abba' brute=2 extend=2 set=2 last=2 buggy=3 substring='ab'
'dvdf' brute=3 extend=3 set=3 last=3 buggy=3 substring='vdf'
'tmmzuxt' brute=5 extend=5 set=5 last=5 buggy=6 substring='mzuxt'
stress: 3000 random strings, correct solutions disagreed with brute force 0 times
stress: buggy version wrong on 1175 of 3000 random strings
random 50k extend_from_each_start -> 41 in 40.4 ms
random 50k window_with_set -> 41 in 7.5 ms
random 50k window_with_last_index -> 41 in 4.5 ms
cyclic 50k extend_from_each_start -> 95 in 237.0 ms
cyclic 50k window_with_set -> 95 in 4.9 ms
cyclic 50k window_with_last_index -> 95 in 5.1 ms
random 2k brute_force -> 33 in 5851.3 ms
"dvdf" is worth tracing by hand too. People who reset the window to empty on a repeat (instead of moving left to just after the old copy) get 2 here. The right answer is 3 ("vdf").
Timings are from Python 3.13 on a shared Linux box, so read them as ratios rather than exact numbers.
Returning the substring itself
Some interviewers (and the “print the longest substring” variant) want the substring itself, not its length. Track where the best window starts:
def longest_substring(s):
last, left, best_start, best_len = {}, 0, 0, 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
if right - left + 1 > best_len:
best_start, best_len = left, right - left + 1
return s[best_start:best_start + best_len]
With a strict > it returns the first longest substring ("ab" for "abba", not "ba"). Say which one you return if there’s a tie.
Java
A 128-slot int[] replaces the hash map. It’s faster and uses constant space, and it’s safe because LeetCode’s input is ASCII.
import java.util.Arrays;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128]; // LeetCode input is ASCII: letters, digits, symbols, spaces
Arrays.fill(last, -1);
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
if (last[ch] >= left) { // previous copy is inside the window
left = last[ch] + 1;
}
last[ch] = right;
best = Math.max(best, right - left + 1);
}
return best;
}
}
Output from java Solution (OpenJDK 25; the repo file adds a main that runs these inputs), including what happens when you pass it something that isn’t ASCII:
"abcabcbb" -> 3
"bbbbb" -> 1
"pwwkew" -> 3
"" -> 0
" " -> 1
"abba" -> 2
"tmmzuxt" -> 5
"café" -> java.lang.ArrayIndexOutOfBoundsException: Index 233 out of bounds for length 128
é is char 233, so the 128-slot array blows up. For LeetCode that’s fine. For production code, use int[256] for Latin-1, or a HashMap<Character, Integer>. And if the text can contain emoji, remember that a Java char is a UTF-16 unit, not a full character.
Go
func lengthOfLongestSubstring(s string) int {
var last [128]int
for i := range last {
last[i] = -1
}
left, best := 0, 0
for right := 0; right < len(s); right++ {
ch := s[right] // a byte; fine for ASCII-only LeetCode input
if last[ch] >= left {
left = last[ch] + 1
}
last[ch] = right
best = max(best, right-left+1)
}
return best
}
Indexing a Go string gives you bytes, not characters. That’s correct for LeetCode. On real text it gives a different, wrong answer without any error. The repo’s main.go runs a byte-keyed version and a []rune version on non-ASCII input:
"éè": len(s)=4 bytes, bytes-map answer=3, rune answer=2
"日本語": len(s)=9 bytes, bytes-map answer=8, rune answer=3
"日本語" is 3 characters, but the byte version reports a substring of 8. If the input isn’t guaranteed to be ASCII, convert with []rune(s) first (or range over the string and track byte offsets).
Complexity
| Approach | Time | Extra space | 50k random chars (Python) |
|---|---|---|---|
| Brute force, set per substring | O(n³) | O(m) | not feasible (2k took 5.85 s) |
| Grow from each start | O(n · m) | O(m) | 40 ms (237 ms worst case) |
| Window, shrink with set | O(n), at most 2n steps | O(m) | 7.5 ms |
| Window, last index | O(n), exactly n steps | O(m) | 4.5 ms |
m is the alphabet size, at most min(n, number of distinct characters). With a fixed 128-entry array the extra space is O(1) in the usual interview sense. With a hash map it’s O(min(n, m)).
Common mistakes
- Missing the
last[ch] >= leftcheck.leftjumps backwards on"abba". This is the bug behind most wrong submissions. - Updating
bestbefore fixingleft. Moveleftfirst, then recordright - left + 1, so you only measure windows that are valid. - Resetting the window on a repeat. Starting over at
right(or clearing the set) loses the characters between the old copy andright."dvdf"returns 2 instead of 3. - Using
ifinstead ofwhilein the set version. One removal isn’t enough when the repeated character is deep inside the window: on"abcb"the secondbmust remove bothaandb. - Confusing substring with subsequence. The longest subsequence without repeats is just the number of distinct characters. That’s a different, trivial problem.
- Assuming ASCII when the input isn’t. A fixed array crashes in Java, and Go byte indexing gives a different answer without any error. Both are covered above.
Related problems
The same “longest window that stays valid” idea solves these. Work them in order:
| Problem | What changes | Difficulty |
|---|---|---|
| 1695. Maximum Erasure Value | Same window, but maximise the sum instead of the length | Medium |
| 904. Fruit Into Baskets | Valid means at most 2 distinct values | Medium |
| 424. Longest Repeating Character Replacement | Valid means length minus top count is at most k | Medium |
| 1004. Max Consecutive Ones III | Valid means at most k zeros | Medium |
| 340. Longest Substring with At Most K Distinct Characters | Generalises 904 (LeetCode Premium) | Medium |
| 76. Minimum Window Substring | Flipped: the shortest window that is valid | Hard |
LeetCode 3 is on the Blind 75, the LeetCode 150 and the DSA master sheet, where you can tick it off once you’ve solved it from memory.
FAQ
What is the time complexity of longest substring without repeating characters?
O(n) with a sliding window: each character enters the window once and leaves at most once. The extra space is O(min(n, m)) for the hash map, or O(1) with a fixed 128-entry array for ASCII input.
Why is it a sliding window problem?
The answer is a contiguous substring, and validity is monotonic: if a window contains a repeat, every larger window around it does too. That lets left only ever move forward, which is the condition for an O(n) sliding window.
Should I use a set or a hash map of last indices?
Either is O(n). The set version follows the standard shrink template and is harder to get wrong. The last-index version does one jump instead of a loop but needs the last[ch] >= left check. In an interview, write the one you can explain clearly, then mention the other.
How do I return the substring and not just its length?
Track the start and length of the best window whenever it improves, and slice at the end: s[best_start:best_start + best_len]. The Python version above does exactly that.
Does the solution work for Unicode strings?
The hash-map versions do in Python, because Python strings index by code point. In Java a fixed int[128] throws on characters above 127, and in Go s[i] is a byte, so multi-byte characters give wrong answers. Use a map keyed by rune (Go) or int code point (Java) when the input isn’t ASCII.
Learn the pattern
- Sliding window technique guide: the three templates and seven more solved problems.
- Sliding window lesson in the free DSA Patterns course, with exercises and a quiz.
- Two pointers guide, for when the pointers start at opposite ends instead.