Quick revision
The short answer
We slide a window over the string with two pointers, left and right, and remember the last index where each character was seen in an int[128] or a map. When the character at right was last seen at an index inside the window (at or after left), we move left to just past that index; then we update the best length as right - left + 1. Each pointer only moves forward, at most n times, so the method is O(n) time with space proportional to the alphabet.
What to remember
In this answer, we replaced the O(n^2) brute force with a sliding window. We kept the last index of each character, moved left to last seen + 1 only when the repeat was inside the window, and updated the best length as right - left + 1. Because both pointers only move forward, the total work is O(n), with space proportional to the alphabet. For full Unicode, we iterated by code points with a HashMap instead of a char-indexed array.
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 over the string with two pointers, left and right, and remember the last index where each character was seen in an int[128] or a map. When the character at right was last seen at an index inside the window (at or after left), we move left to just past that index; then we update the best length as right - left + 1. Each pointer only moves forward, at most n times, so the method is O(n) time with space proportional to the alphabet.
Why this question is asked
This problem is the standard introduction to the sliding window technique, which shows up whenever we need the best contiguous range in a sequence: the longest session without an error, the shortest span of logs that covers all services, the busiest five minutes. Interviewers like it because the brute force is easy to write and slow, and the efficient version depends on one insight about not moving backwards. In this answer, we will start with the brute force, build the window step by step, trace it on 'abcabcbb', explain carefully why it is linear, and finish with full Unicode support.
1Starting From the Brute Force
A substring is a contiguous run of characters, unlike a subsequence, which may skip characters. The brute force tries every starting index and extends the substring until it meets a repeated character, using a set to detect repeats. That is O(n^2) in the worst case, and for a 100,000 character string about 5 billion steps, which is too slow. Notice what it wastes: after finding that 'abca' repeats 'a', it starts again from index 1 and rechecks 'bc', which it already knows contains no repeats. The sliding window keeps that knowledge.
2Building the Sliding Window
We keep a window s[left..right] that never contains a repeated character. We move right forward one character at a time. If the new character already appears inside the window, the window is no longer valid, and the smallest fix is to move left to just past the earlier copy of that character. To find the earlier copy instantly, we store, for every character, the last index where we saw it. For ASCII text an int[128] is enough and faster than a map; we fill it with -1 to mean 'not seen'.
The condition last[c] >= left is the important detail. A character may have been seen before but outside the current window, because left has already moved past it. In 'abba', when right reaches the final 'a', its last index is 0 but left is already 2, so the old 'a' no longer matters. Without the >= left check, left would jump back to 1, the window would wrongly contain two 'b's, and we would report 3 instead of 2.
3Tracing the Window on 'abcabcbb'
Watching the pointers makes the idea concrete. The window grows while characters are new, and when a repeat appears, left jumps forward, never back.
| right, char | last seen | left after | window, length |
|---|---|---|---|
| 0, a | -1 | 0 | a, 1 |
| 1, b | -1 | 0 | ab, 2 |
| 2, c | -1 | 0 | abc, 3 |
| 3, a | 0 | 1 | bca, 3 |
| 4, b | 1 | 2 | cab, 3 |
| 5, c | 2 | 3 | abc, 3 |
| 6, b | 4 | 5 | cb, 2 |
| 7, b | 6 | 7 | b, 1 |
4Why It Is O(n)
It can look as if the method does more than n steps, because both pointers move. But count the moves separately. right moves forward exactly once per loop iteration, n times in total. left only ever moves forward, never back, and it can never pass right, so over the whole run it moves forward at most n positions in total, even though a single jump may cover several positions. Each iteration does constant work besides the jump: one array read, one array write, one comparison. So the total work is O(n). This argument, that two pointers each move forward at most n times, is the general proof for every sliding window algorithm.
Space is O(alphabet): 128 ints for ASCII, which is constant with respect to n. A version that stores characters in a HashSet and removes them one by one while moving left also runs in O(n), with up to 2n set operations, but the last-index array is faster and simpler.
5Supporting Full Unicode
Java's char is a UTF-16 code unit, not a character. Characters outside the Basic Multilingual Plane, such as most emoji, are stored as two chars, a surrogate pair. The int[128] version would throw ArrayIndexOutOfBoundsException on any char above 127, and an int[65536] version indexed by char would treat the two halves of an emoji as separate characters. For general text we iterate by code point and use a HashMap<Integer, Integer> from code point to its last position.
Notice that the length we return is now in code points, which is usually what a person means by characters. If the interviewer asks for UTF-16 units, we would say so explicitly. Combining characters, such as e followed by a combining accent, are still two code points; treating them as one would need java.text.BreakIterator or normalization, which is worth mentioning but rarely required.
6Follow-up questions
How would you return the substring itself, not only its length?
Record the left index whenever best improves, as bestStart = left. At the end return s.substring(bestStart, bestStart + best). It adds no extra complexity.
What if at most k distinct characters are allowed instead of none repeated?
We keep a map from character to count in the window. Moving right adds one; while the map has more than k keys, we decrement the count at left, remove the key when it reaches zero, and move left forward. It is still O(n) by the same two pointer argument.
Why int[128] instead of a HashMap for ASCII?
An array index is a single memory access with no hashing, no boxing and no allocation, while HashMap<Character, Integer> boxes both key and value. For a tight loop over long strings, the array is several times faster.
7Conclusion
In this answer, we replaced the O(n^2) brute force with a sliding window. We kept the last index of each character, moved left to last seen + 1 only when the repeat was inside the window, and updated the best length as right - left + 1. Because both pointers only move forward, the total work is O(n), with space proportional to the alphabet. For full Unicode, we iterated by code points with a HashMap instead of a char-indexed array.
Open with
I would use a sliding window with two pointers. The window from left to right always contains unique characters. I move right one step at a time and keep an int array of 128 entries with the last index where each character was seen, initialised to minus one.
Then, if they want more
When the character at right was last seen at an index greater than or equal to left, so inside the current window, I move left to that index plus one, which is the smallest move that removes the duplicate. Then I store right as the character's last index and update the best length as right minus left plus one.
The greater than or equal to left check matters: in 'abba', the final 'a' was seen at index zero, but left is already at two, so I must not move left backwards. For 'abcabcbb' the answer is three.
It is O(n) because right moves forward n times and left only ever moves forward, never past right, so it also moves at most n positions in total, and each step is constant work. Space is the size of the alphabet, 128 ints for ASCII.
For full Unicode I would iterate over code points with codePoints and use a HashMap from code point to index, because Java chars are UTF-16 units and an emoji takes two of them.
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/algorithms-and-data-structures/2d3788c6a6/