Longest Substring Without Repeating Characters solution explained
The standard solution to Longest Substring Without Repeating Characters is a sliding window: extend the right edge one character at a time, and when a character repeats inside the window, move the left edge just past its previous position. Remembering each character's latest index lets the left edge jump, so the whole scan is O(n) time with memory bounded by the alphabet size.
By Evin JohnPublished 7 min read
What you are asked to find
Given a string, look at every stretch of consecutive characters, called a substring, and keep only those where all characters are different from each other. Report the length of the longest one. Order matters and characters must be next to each other, so this is not the same as counting distinct letters in the whole string, and it is not a subsequence where you could skip characters.
| Input | Longest valid substring | Length |
|---|---|---|
planet | planet | 6 |
xyzzyx | xyz or zyx | 3 |
abba | ab or ba | 2 |
mmmm | m | 1 |
| empty string | nothing | 0 |
Clarify the character set first. Lowercase letters only, printable ASCII, or any Unicode text? The answer decides whether a fixed-size array can replace the dictionary, and in some languages it decides what counts as one character. Also ask whether the interviewer wants the length or the substring itself.
What the interviewer is checking
This is the problem many people meet the sliding window on, and interviewers use it for exactly that reason. They want to see you notice that once a window is free of repeats, its inner part stays free of repeats, so there is no need to restart from scratch. They also watch for the classic bug in the jump version, where the left edge moves backward, which the input abba exposes immediately.
- Return the substring, not just its length. Record the start index whenever the best length improves, then slice once at the end.
- Allow at most k distinct characters. Keep counts in the window and shrink from the left while there are more than k keys.
- Allow each character at most twice. Shrink while the count of the newest character exceeds two.
- The alphabet is small and fixed. Replace the dictionary with an array of 26 or 128 slots, which bounds memory by a constant.
- The text arrives as a stream. The window works online; you only need the last positions and the current start, not the whole string.
First pass: try every starting point
Pick each index as a start, then walk right while adding characters to a set, and stop at the first repeat. The set makes the repeat check O(1), so this is O(n²) in time, or O(n times the alphabet size) since no run can be longer than the alphabet. It is a fair brute force and it already shows the shape of the better answer: the inner loop is rebuilding a window that the previous start had mostly built already.
def longest_run_brute(text):
best = 0
for i in range(len(text)):
used = set()
for j in range(i, len(text)):
if text[j] in used:
break
used.add(text[j])
best = max(best, len(used))
return bestSliding window, version one: shrink step by step
Keep two indexes, lo and hi, and a set of the characters between them. Move hi forward one character at a time. If the new character is already in the set, remove characters from the left, moving lo forward, until it is not. Then add it and compare the window's length with the best so far. Each index enters the window once and leaves at most once, so the total work is O(n) even though there is a loop inside a loop.
def longest_run_set(text):
inside = set()
lo = best = 0
for hi, ch in enumerate(text):
while ch in inside:
inside.remove(text[lo])
lo += 1
inside.add(ch)
best = max(best, hi - lo + 1)
return bestSliding window, version two: jump the left edge
Instead of crawling, remember for each character the index just after its most recent appearance. When that character shows up again, the window must start at least there. Take the maximum of the current start and that stored value, because the stored value may point to a spot the window already left behind. In abba, when the second a arrives the window already begins at the second b, and jumping back to just after the first a would wrongly put both b characters inside the window again.
def longest_run(text):
resume_at = {} # char -> index just past its latest occurrence
start = best = 0
for i, ch in enumerate(text):
start = max(start, resume_at.get(ch, 0))
best = max(best, i - start + 1)
resume_at[ch] = i + 1
return bestfunction longestRun(text) {
const resumeAt = new Map(); // char -> index just past its latest occurrence
let start = 0;
let best = 0;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (resumeAt.has(ch)) start = Math.max(start, resumeAt.get(ch));
best = Math.max(best, i - start + 1);
resumeAt.set(ch, i + 1);
}
return best;
}The JavaScript version reads text[i], which is one UTF-16 code unit. An emoji is two code units, so it would be treated as two characters. For plain letters this never matters; for user-entered text, iterate with Array.from(text) first and say why.
Complexity at a glance
| Method | Time | Extra space |
|---|---|---|
| Every substring checked from scratch | O(n³) | O(k) |
| Every start, extend with a set | O(n²), or O(n·k) | O(k) |
| Window that shrinks one step at a time | O(n) | O(min(n, k)) |
| Window that jumps using last positions | O(n) | O(min(n, k)) |
Both window versions are linear. The jump version does fewer operations on strings with long repeats, but the set version is easier to get right under pressure. Either is a strong answer if you can state why it is linear.
Inputs worth testing
- The empty string, which should return 0 without touching any index.
- A single character, and a run of one character repeated, such as
mmmm. - A string with no repeats at all, where the answer is the full length.
abba, which catches a left edge that moves backward.- A repeat at the very end, such as
abcda, where the best window is found before the repeat. - Spaces and punctuation, which count as characters like any other.
Frequent errors
- Setting the start to the stored position without taking the maximum.
- Updating the best length before moving the start, which counts a window that still holds the repeat.
- Off-by-one window lengths: with inclusive indexes, the length is
hi - lo + 1. - Confusing substring with subsequence and counting distinct characters in the whole string.
- Claiming O(n²) for the set version because of the nested while loop. Say why it is linear: the left edge only moves forward.
Talking through your answer
Fictional example
- Candidate
- Trying every start is quadratic, and it keeps rebuilding the same window. Once a stretch has no repeats, any shorter stretch inside it has none either, so I can keep a window and only fix it when a repeat arrives.
- Candidate
- I move the right edge forward. For each character I store the index just past where I last saw it. On a repeat I move the start to that spot, but never backward, so I take the max.
- Candidate
- Both edges only move forward, so it is linear time, and the map holds at most one entry per distinct character. Let me trace abba to show the max matters.
Other problems in this set
The dictionary of positions here is a close relative of the value-to-index map in Two Sum. The same one-direction sweep, applied to ranges instead of characters, solves Merge Intervals. For a structure that also tracks what was used most recently, move on to the LRU Cache walkthrough. All eight are on the coding problems hub.
Rehearsing with Natively
When you practice, Natively can read a string problem like this one from a screenshot and point toward a sliding window and the cases to test, such as a repeat that sits outside the current window. It works on Mac and Windows and transcribes your mock interview, so you can review whether you explained why the window is linear. Learn more about an AI interview assistant built for practice like this.
Questions people ask
What is the optimal solution for longest substring without repeating characters?
A sliding window. Move the right edge one character at a time and, when a character repeats inside the window, move the left edge just past its previous position. Both edges only move forward, so it runs in O(n) time.
Why take the maximum when moving the left edge?
The stored position of a character can lie before the current window. Without the maximum, the left edge can jump backward and re-admit a repeat, which is exactly what the input abba exposes.
What is the space complexity?
O(min(n, k)), where k is the size of the character set, because the map holds at most one entry per distinct character. With a fixed alphabet, that is constant.
Is this a sliding window problem?
Yes. It is one of the most common introductions to the pattern, which also solves problems like the longest stretch with at most k distinct characters.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
