Quick revision
The short answer
Finding the longest substring with no repeated characters is a sliding window problem. We move a right edge across the string, remember where each character was last seen, and when the new character's old copy is inside the window we jump the left edge just past it, never backwards. The longest window seen is the answer, in O(n) time and O(k) space for k distinct characters.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Check every substring from scratch | O(n^3) | O(k) |
| Every start, extended with a set | O(n^2) | O(k) |
| Window with a set, removing one by one | O(n), up to 2n steps | O(k) |
| Window with last seen positions, jumping | O(n) | O(k) |
What to remember
We found the longest substring without repeats by sliding a window along the string. right takes in one character per step, lastSeen remembers where each character was last seen, and when the new character's old copy is inside the window, left jumps just past it, never backwards. Measuring the window after each step gives the answer in O(n) time. The clue to remember is the longest contiguous run under a rule that a single added character can break: keep a window whose edges only move forwards, and repair it from the left.
1What the question asks, told with a paper frame
Imagine a long line of letters printed on a strip of paper, and a small paper frame you lay on top of it. The frame has two edges you can slide independently, a left edge and a right edge, and you can see only the letters between them. Your task is to make the frame as wide as possible, with one rule: no letter may appear twice inside the frame. That frame is what programmers call a window, and this whole problem is about moving its two edges cleverly.
In Java terms we are given a String s and must return the length of its longest substring with no repeated characters. A substring is a run of characters that sit next to each other in the string, with nothing skipped. So in "abcabcbb", "cab" is a substring, but "acb" is not, because it skips letters.
Let us keep the example "abcabcbb" for the whole article. By hand, start at the first letter and read on until a letter repeats: a, b, c, and then a again, so "abc" has length 3. Starting at the second letter gives "bca", length 3 again. Keep trying and you will find nothing longer, so the answer is 3. A second example is worth one look. For "pwwkew" the answer is 3, from "wke". "pwke" is longer, but it is not a substring, because it skips the second w.
The string "abcabcbb" with one longest run of distinct letters marked. "bca", "cab" and the second "abc" are just as long.
- string
- "abcabcbb"
- answer
- 3
1In "abcabcbb" the first three letters, "abc", have no repeat, and no run without a repeat is longer, so the answer is 3.
What to assume
- Do we return the length or the substring itself?
- The length.
- Are upper and lower case different?
- Yes, we compare Java char values exactly, so A and a are different, and spaces and punctuation count as characters.
- What characters can appear?
- Any. The empty string has answer 0.
This problem can feel slippery, because there are many substrings and it is hard to see how to check them all. It is smaller than it looks. We will see that a single walk along the string, moving each edge of the frame only forwards, is enough.
A careful candidate asks a few questions first. Do we return the length or the substring itself? The length, though the FAQs show how to keep the substring too. Are upper and lower case different? Yes, we compare Java char values exactly, so A and a are different, and spaces and punctuation count as characters. What characters can appear? Any, so we use a HashMap. The empty string has answer 0.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a sliding window problem
When a beginner first reads this question, the natural plan is to look at every substring and check whether it has a repeat. That is honest and correct, and it is our brute force. But before writing it, let us read the question slowly and collect the clues, one at a time.
The first clue is the word substring. A substring is contiguous, a single unbroken run. Any run can be described by just two numbers, where it starts and where it ends. So whatever we do, we are really choosing two indexes, and the question is how to choose them without trying every pair.
The second clue is the word longest. We are looking for the biggest run that obeys a rule. When a question asks for the longest or shortest run with some property, it is worth asking how the property behaves when the run grows or shrinks.
The third clue is the rule itself, no repeated characters, and it behaves very kindly. If a run has no repeats, every shorter run inside it has none either. And when we add one character on the right, only that new character can cause a repeat. So we can keep a run that is valid, grow it on the right, and when it breaks, repair it by removing characters from the left, never from the middle.
Together the clues point to the sliding window pattern. A window is a run of the array or string between two indexes, left and right, like our paper frame. Sliding means both edges only ever move forwards, right to take in new characters and left to drop old ones. The general rule to carry away is this. When a question asks for the longest or shortest contiguous run satisfying a condition, and adding an element on one side or removing one on the other changes the condition in a way you can update quickly, use a window whose two edges only move forwards.
Some patterns look similar but do not fit. Two pointers coming from both ends suit sorted data or mirror shapes like palindromes, and here the order of letters is arbitrary. Prefix sums answer questions about totals over ranges, not about which characters a range holds. Dynamic programming could compute the longest valid run ending at each index, but that is the sliding window written another way.
3The honest first attempt, trying every start
The honest first attempt tries every possible starting index i. From each start it moves an end index j forward one character at a time, keeping a set of the characters seen so far. A set is a collection that keeps each value only once, and its add method returns false when the value is already there. The moment add returns false, the run starting at i cannot grow any further, so we record its length and move to the next start.
Let us do it by hand on "abcabcbb". From index 0 we read a, b, c and then meet a repeat, so the run is 3, after 4 checks. From index 1 we read b, c, a and meet b, length 3, 4 checks. Index 2 and index 3 also give length 3 after 4 checks each. Index 4 gives "bc", index 5 gives "cb", index 6 gives "b", and index 7 gives "b". Adding up, the method makes 25 checks to find the answer 3 in a string of 8 letters.
In general there are n starts, and from each start we may read up to n characters, so the time grows like n times n, written O(n^2), read as order n squared. For a string of 100,000 distinct characters that is about five billion steps. The set holds at most one copy of each character, so the space is O(k), where k is the number of different characters that can appear.
So where is the waste? Look at what happens after the run from index 0 stops at the second a. The brute force throws everything away and starts again at index 1, where it reads b and c again, letters it had just confirmed were fine. Only one thing actually went wrong, the old a at index 0 clashed with the new a at index 3. Everything between them, "bc", was still valid.
So let us ask the question that leads further. When the run breaks, instead of starting again from scratch, can we keep the valid part and only move the left edge past the old copy of the repeated letter?
4Getting to the sliding window, one observation at a time
Let us keep a window from left to right that never contains a repeated character, and move right forward one character at a time. If the new character c is not already in the window, the window simply grows, and its length right - left + 1 might be a new best. If c is already in the window, we must move left forwards until the old copy of c has left the frame.
How do we know where the old copy is? A first version could keep a set and remove characters from the left one by one until c disappears. That already works in O(n), because each character enters and leaves the set at most once. But we can do better with a map, which works like the index at the back of a book, telling you on which page each word last appeared. Our map, lastSeen, tells us at which index each character was last seen. When we read c at right, we look up prev = lastSeen.get(c), and if the old copy is inside the window, we jump left straight to prev + 1, just past it, in one step.
The last a was seen before, but outside the window. The check prev >= left keeps left where it is.
- window
- "ab"
- length
- 2
- best
- 2
- lastSeen
- a:0 b:1
1On "abba", right reads a and then b. Both are new, so the window grows to "ab" and best is 2.
- window
- "b"
- length
- 1
- best
- 2
- lastSeen
- a:0 b:2
2right reads the second b, last seen at 1, inside the window. left jumps to 2, and the window is just "b".
- a last seen
- 0, outside
- left
- 2
- wrong left
- 1, gives "bba"
3right reads the last a.
lastSeensays index 0, but 0 is left of the window. Jumping left back to 1 would bring in b, b, a repeat.- window
- "ba"
- length
- 2
- best
- 2
- lastSeen
- a:3 b:2
4Because 0 is less than left, the check prev >= left is false and left stays at 2. The window is "ba", and best stays 2.
Now comes the question that catches most beginners. lastSeen remembers every character we have ever seen, not only those inside the window. So what if the old copy is already to the left of the window? The picture above, on "abba", shows exactly this. When the last a arrives, lastSeen says a was at index 0, but left is already at 2. If we blindly set left = 0 + 1 = 1, the left edge would move backwards and bring the b at index 1 back into the window, together with the b at index 2, a repeat. So we jump only when prev >= left, which means the old copy really is inside the window.
This also shows the most tempting mistake. Writing left = prev + 1 without the check looks right on "abcabcbb" and passes the first tests, and fails on "abba" by returning 3 instead of 2. Moving left backwards is never needed, because the part we already dropped contained a clash.
Why is the method correct? Every substring with no repeats ends at some index. When right is at that index, our window is the longest valid run ending there, because left was moved only as far as needed to remove a clash. So by checking the window length at every right, we look at the best candidate for every possible end, and the largest of them is the answer.
After the check we always record the new position with lastSeen.put(c, right), so the map holds the latest index of every character, and then update best. Both edges only ever move forwards, so the whole walk is a single pass.
5Watching the window slide along "abcabcbb"
The picture plays the method on "abcabcbb", one frame per step of the loop, using the values the Java method printed. The letters inside the window are marked, the letter right has just read is marked as now, and letters the left edge has passed are faded. The panel shows the window, its length, best so far and the lastSeen map.
Watch the left edge. It jumps only when a repeat inside the window appears, and it never moves backwards.
Marked letters are inside the window, faded letters are behind the left edge. right moves one step per frame; left jumps only past a repeat inside the window.
- window
- ""
- length
- 0
- best
- 0
- lastSeen
- empty
1Before the loop, left is 0, best is 0 and
lastSeenis empty. The window has not started yet.- window
- "a"
- length
- 1
- best
- 1
- lastSeen
- a:0
2right reads a at index 0.
lastSeenhas no a, so the window simply grows to "a", and best becomes 1.- window
- "ab"
- length
- 2
- best
- 2
- lastSeen
- a:0 b:1
3right reads b. There is no b in
lastSeen, so the window grows to "ab" and best becomes 2.- window
- "abc"
- length
- 3
- best
- 3
- lastSeen
- a:0 b:1 c:2
4right reads c, also new. The window is "abc", and best becomes 3, the answer, though we do not know that yet.
- window
- "bca"
- length
- 3
- best
- 3
- lastSeen
- a:3 b:1 c:2
5right reads a, last seen at 0, which is inside the window. left jumps to 0 + 1 = 1, the window is "bca", and best stays 3.
- window
- "cab"
- length
- 3
- best
- 3
- lastSeen
- a:3 b:4 c:2
6right reads b, last seen at 1, inside the window. left jumps to 2, the window is "cab", still length 3.
- window
- "abc"
- length
- 3
- best
- 3
- lastSeen
- a:3 b:4 c:5
7right reads c, last seen at 2, inside the window. left jumps to 3, the window is "abc" again, length 3.
- window
- "cb"
- length
- 2
- best
- 3
- lastSeen
- a:3 b:6 c:5
8right reads b, last seen at 4. left jumps over two places to 5, and the window shrinks to "cb", length 2.
- window
- "b"
- length
- 1
- best
- 3
- lastSeen
- a:3 b:7 c:5
9right reads b again, last seen at 6. left jumps to 7, the window is just "b", and the loop ends with best 3.
- answer
- 3
- window
- "abc"
10The longest window we met was "abc" from index 0 to 2, so the method returns best, 3.
Let us read the important frames back. The window grows to "abc" in the first three steps, and best becomes 3. Then the a at index 3 finds its old copy at index 0, inside the window, so left jumps to 1. The window "bca" is still length 3. The same happens for b and c, and the window slides along, keeping its length.
At index 6 the frame changes shape. The b was last seen at 4, so left jumps two places at once, from 3 to 5, and the window shrinks to "cb". That jump is what the map buys us; a set would have needed two separate removals. At index 7, b repeats again, left jumps to 7, and the window is just "b".
The loop has visited each of the 8 letters exactly once, making 8 lookups against the 25 checks of the brute force, and returns best, 3.
6The complete Java program
Here is the full program. A HashMap from Character to Integer works for any characters. main runs our example, the three other classic inputs, including the "abba" trap, and the empty string, and each comment shows what that line prints.
Let us read longest in the order it runs. We create the lastSeen map, and set best and left to 0, so the window starts at the beginning of the string and nothing has been measured yet.
The for loop moves right across the string, one character per round. For each character c, we look up prev, its last index, which is null if c has never been seen. Then comes the important line. If prev is not null and prev >= left, the old copy is inside the window, so left = prev + 1 moves the left edge just past it. We use Integer rather than int for prev, because only an object can be null.
Next, lastSeen.put(c, right) records the newest index of c, overwriting the old one, and best = Math.max(best, right - left + 1) keeps the longest window seen. The + 1 is there because a window from index 2 to index 4 holds three characters, not two.
When the loop ends we return best. So main prints 3 for "abcabcbb", 1 for "bbbbb", where the window is always one letter, 3 for "pwwkew", 2 for "abba" thanks to the check, and 0 for the empty string, where the loop never runs. When the input is known to be plain ASCII, an int[128] array filled with -1 can replace the map with the same logic.
7How much it costs, and the cases at the edges
Let us count on the example first. right visited each of the 8 letters once, and each visit did one map lookup, one put and one comparison. left also moved only forwards, and jumps cost one assignment each, so there is no hidden inner loop. For n characters that is about n steps, so the time is O(n), with map operations taking constant time on average.
The map holds at most one entry per distinct character, so the space is O(min(n, k)), where k is the size of the alphabet. For a fixed alphabet such as ASCII that is at most 128 entries, effectively O(1).
| Approach | Time | Extra space |
|---|---|---|
| Check every substring from scratch | O(n^3) | O(k) |
| Every start, extended with a set | O(n^2) | O(k) |
| Window with a set, removing one by one | O(n), up to 2n steps | O(k) |
| Window with last seen positions, jumping | O(n) | O(k) |
The edge cases need no special code. The empty string returns 0 because the loop never runs. A string of one repeated letter keeps a window of length 1. A string of all different letters never moves left, so the window grows to the whole string. And the stale copy, as in "abba", is handled by the prev >= left check.
A common beginner slip is to update best before moving left. Then the length is measured on a window that still contains the repeat, and "abcabcbb" would wrongly report 4. Moving left first, then measuring, keeps every measured window valid.
8Follow-up questions
How would you return the substring itself, not just its length?
We keep one more variable, bestStart, next to best. Whenever the window length right - left + 1 is larger than best, we set best to that length and bestStart to left. When the loop ends, s.substring(bestStart, bestStart + best) is the answer. For "abcabcbb" bestStart stays 0 and we return "abc". The cost does not change.
How does this change for the longest substring with at most k distinct characters?
The window idea is the same, only the rule changes. Instead of last positions we keep a count of each character inside the window. When right adds a character and the number of distinct characters becomes more than k, we move left forward one step at a time, lowering the count of the character that leaves and removing it from the map when its count reaches 0, until only k distinct characters remain. Each character enters and leaves once, so it is still O(n).
Why not use an int array instead of a HashMap?
When we know the string contains only ASCII characters, an int[128] filled with -1 works exactly like the map. lastSeen[c] gives the last index, and -1 means never seen. It is faster because there is no boxing of chars and ints into objects. For arbitrary Unicode text the map is the safer choice, because it does not need to know the alphabet in advance.
9Conclusion
We found the longest substring without repeats by sliding a window along the string. right takes in one character per step, lastSeen remembers where each character was last seen, and when the new character's old copy is inside the window, left jumps just past it, never backwards. Measuring the window after each step gives the answer in O(n) time. The clue to remember is the longest contiguous run under a rule that a single added character can break: keep a window whose edges only move forwards, and repair it from the left.
Open with
Let me confirm the details first. I return the length, characters are compared exactly so case matters, and the string can contain any characters, so I will use a HashMap.
Then, if they want more
The brute force tries every start and extends with a set until a repeat, which is O(n squared), and it rereads characters it already knew were fine. Since the question asks for the longest contiguous run under a rule that one new character can break, I will use a sliding window.
I keep left and best at 0 and a map from each character to the index where I last saw it. For each right, I look up the character's last index. If it exists and is at least left, the repeat is inside the window, so I move left to that index plus one.
I never move left backwards, which is what the check protects against in a case like abba. Then I record the new index and update best with right minus left plus one. Each character is processed once, so the time is O(n), and the space is O(k) for k distinct characters.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 38 times in that collection. How it is counted
- Official documentation
- HashMap (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the length of the longest substring with no repeated characters.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-length-of-the-longest-substring-with-no-repeated-charac-13b71f/
Coding patterns, question 4 of 15 Back to the path
More sliding window questions