Quick revision
The short answer
We slide a window [left, right] over the string and keep, for each character, the last index where we saw it. When the character at right was last seen inside the window, we move left just past that earlier occurrence, using left = Math.max(left, last + 1) so left never moves backwards; then we record right - left + 1 as a candidate length. Each index enters the window once and leaves it at most once, so the whole scan is O(n) time and O(k) space for an alphabet of k characters.
What to remember
In this answer, we saw how a sliding window solves the longest substring without repeating characters. We remember the last index of each character, move left past an earlier occurrence only when it is inside the window, record right - left + 1, and use Math.max so left never moves backwards, which is the bug the "abba" input exposes. Because each pointer only moves forward, the total work is O(n), with O(k) space for the alphabet, and the same window idea adapts to returning the substring and to the at most two distinct characters variant.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We slide a window [left, right] over the string and keep, for each character, the last index where we saw it. When the character at right was last seen inside the window, we move left just past that earlier occurrence, using left = Math.max(left, last + 1) so left never moves backwards; then we record right - left + 1 as a candidate length. Each index enters the window once and leaves it at most once, so the whole scan is O(n) time and O(k) space for an alphabet of k characters.
Why this question is asked
The sliding window is one of the most useful patterns in coding interviews, and it shows up in real code too, for example in rate limiting, deduplicating events in a time range, or finding the longest clean stretch in a log. Interviewers like this question because the brute-force answer is easy, the linear answer needs a clear idea, and there is a classic off-by-one bug that separates people who understand the window from people who remember the code. In this answer, we will recap what a window is, build the solution step by step, trace it on "pwwkew", see the bug that moves left backwards, explain why the algorithm is linear, and answer the follow-ups about returning the substring and allowing two distinct characters.
1A Quick Recap of the Problem and the Window
A substring is a run of consecutive characters, so in "pwwkew" the string "wke" counts but "pwke" does not, because its letters are not next to each other. We want the longest substring in which no character appears twice. For "abcabcbb" that is "abc" with length 3, and for "pwwkew" it is "wke", also 3.
The brute-force way checks every substring, which is O(n^2) substrings, each checked in up to O(n) time. A window does better. We keep two indexes, left and right, and the window is the substring between them. We only ever move right forward to add a character, and left forward to drop characters, and we keep the rule that the window never contains a repeated character. Whenever the rule holds, the window's length is a candidate answer.
2Building the Solution
To move left quickly, we remember where we last saw each character. When the new character at right was already seen at an index inside the current window, the window must start just after that index. Then we record the new position of the character and update the best length.
| right | char | last seen | left | window, length |
|---|---|---|---|---|
| 0 | p | never | 0 | p, 1 |
| 1 | w | never | 0 | pw, 2 |
| 2 | w | 1 | 2 | w, 1 |
| 3 | k | never | 2 | wk, 2 |
| 4 | e | never | 2 | wke, 3 |
| 5 | w | 2 | 3 | kew, 3 |
Notice that left jumps directly to the right place instead of moving one step at a time. A slightly slower but equally linear variant keeps a HashSet of the characters in the window and removes s.charAt(left++) until the duplicate is gone; it is easier to adapt to other window rules, as we will see in the follow-up.
For text that is not ASCII, we replace the int[128] with a HashMap<Character, Integer>, or work with code points if emoji must count as one character.
3The Bug That Moves left Backwards
A common mistake writes left = last[c] + 1 without Math.max. It passes "abcabcbb" and "pwwkew", which is why it survives quick testing, but it fails on "abba".
The reason is that last[c] remembers occurrences that are no longer in the window. At right = 3, the earlier a at index 0 was already dropped when left jumped to 2. Using it again drags left back to 1, and the window suddenly contains two b's. Math.max says: an old occurrence only matters if it is inside the current window.
4Why the Algorithm Is O(n)
In the loop, right moves forward exactly n times. left also only moves forward, and it can never pass right, so over the whole run it moves at most n positions in total. Every step does a constant amount of work: one array read, one array write and two max calls. So the total work is proportional to n, even though left sometimes jumps by several positions at once.
This is the general argument for sliding windows: we do not count the work per step, we count how far each pointer travels in total. In the HashSet variant the inner while loop looks like it could make the algorithm quadratic, but each character is added once and removed at most once, so it is O(n) as well, at most 2n set operations. The space is O(k), where k is the alphabet size: 128 ints for ASCII, or at most min(n, k) map entries in general.
5Follow-up questions
How would you return the substring itself?
I keep one more variable, bestStart. Whenever right - left + 1 is greater than best, I set best to that length and bestStart to left. At the end I return s.substring(bestStart, bestStart + best). This costs nothing extra in complexity, and if several substrings share the maximum length, using a strict greater-than returns the first one.
What changes if at most two distinct characters are allowed?
The window rule changes from no repeats to at most two distinct characters, so the jump trick no longer applies. I keep a HashMap from character to its count inside the window. For each right, I add the character; while the map has more than two keys, I decrement the count of s.charAt(left), remove it when it reaches zero, and move left forward. Then I record right - left + 1. It is still O(n), because each character enters and leaves the window once, and the map never holds more than three entries.
Why not check every substring with a HashSet?
That is the brute force: there are about n^2 / 2 substrings and each check takes up to n steps, so it is O(n^3), or O(n^2) if we extend each start until the first repeat. For a 100,000-character input that is billions of steps, while the window does about 100,000.
6Conclusion
In this answer, we saw how a sliding window solves the longest substring without repeating characters. We remember the last index of each character, move left past an earlier occurrence only when it is inside the window, record right - left + 1, and use Math.max so left never moves backwards, which is the bug the "abba" input exposes. Because each pointer only moves forward, the total work is O(n), with O(k) space for the alphabet, and the same window idea adapts to returning the substring and to the at most two distinct characters variant.
Open with
I would use a sliding window. I keep two indexes, left and right, and an array of the last index where I saw each character, initialised to minus one.
Then, if they want more
For each right, I look up the character's last position, and if that position is inside the current window, I move left to one past it.
I write that as left equals Math.max of left and last plus one, because the last position may be an old one that is already outside the window, and without the max, left would move backwards.
The input abba shows that bug: at the final a, the old a at index zero would pull left back to one and the window would contain two b's. After moving left, I store the new last index and update the best length with right minus left plus one.
For abcabcbb that gives 3, and for pwwkew it gives 3 for wke. It is O(n) because right moves forward n times and left only moves forward, so together they travel at most 2n positions, with constant work per step. Space is the size of the alphabet, 128 ints for ASCII or a HashMap otherwise.
To return the substring I would also track where the best window started, and for at most two distinct characters I would switch to a count map and shrink from the left while it has more than two keys.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "Write a Java method that returns the length of the longest substring without repeating...": https://scrivio-interview-library.netlify.app/java/coding-problems/bfd1494c92/