Skip to lesson

Longest substring without repeating characters

Finding the length of the longest substring without repeating characters is one of the most frequently asked interview problems in the world. It showcases the progression from a step-by-step shrinking window with a Set to a direct-jump window using last-seen indices.

Window with a set

Given a string s, we want the maximum length of a contiguous substring s[left .. right] that contains no duplicate characters. Notice that substring means contiguous ("pwk" in "pwwkew"), whereas a subsequence ("pwke") allows skipping characters.

  1. Create Set<Character> window = new HashSet<>() and set left = 0, maxLen = 0.
  2. For right = 0 .. s.length() - 1, read char ch = s.charAt(right).
  3. While window.contains(ch), call window.remove(s.charAt(left)) and increment left.
  4. Add ch to window and update maxLen = Math.max(maxLen, right - left + 1).

Example 1 · Brute force: grow from every start until a repeat (O(n²) time, O(k) space)

LongestSubstringBrute.javaJava
import java.util.HashSet;import java.util.Set;
public class LongestSubstringBrute {    public static int lengthOfLongestSubstring(String s) {        int best = 0;        for (int start = 0; start < s.length(); start++) {            Set<Character> seen = new HashSet<>();            for (int end = start; end < s.length(); end++) {                if (!seen.add(s.charAt(end))) {                    break;                }            }            best = Math.max(best, seen.size());        }        return best;    }
    public static void main(String[] args) {        System.out.println("abcabcbb -> " + lengthOfLongestSubstring("abcabcbb"));        System.out.println("bbbbb    -> " + lengthOfLongestSubstring("bbbbb"));        System.out.println("pwwkew   -> " + lengthOfLongestSubstring("pwwkew"));    }}
Output
abcabcbb -> 3
bbbbb    -> 1
pwwkew   -> 3

What this code does

  • Each start index builds a fresh set and stops at the first repeated character. Up to n starts times up to n characters gives O(n²) time.
  • Starting again from start + 1 re-reads characters that were already known to be unique. A window can keep them.

Example 2 · Better: shrinking window with a HashSet (O(n) time, O(k) space)

LongestSubstringSetDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class LongestSubstringSetDemo {    public static int lengthOfLongestSubstringSet(String s) {        Set<Character> window = new HashSet<>();        int left = 0;        int maxLen = 0;
        for (int right = 0; right < s.length(); right++) {            char ch = s.charAt(right);            while (window.contains(ch)) {                window.remove(s.charAt(left));                left++;            }            window.add(ch);            maxLen = Math.max(maxLen, right - left + 1);        }        return maxLen;    }
    public static void main(String[] args) {        System.out.println("abcabcbb -> " + lengthOfLongestSubstringSet("abcabcbb"));        System.out.println("bbbbb    -> " + lengthOfLongestSubstringSet("bbbbb"));        System.out.println("pwwkew   -> " + lengthOfLongestSubstringSet("pwwkew"));    }}
Output
abcabcbb -> 3
bbbbb    -> 1
pwwkew   -> 3

What this code does

  • When right hits the second 'w' in pwwkew (index 2), the while loop removes 'p' (index 0) and the first 'w' (index 1) so the window becomes [2..2].
  • Each character enters and leaves the HashSet at most once, giving O(n) time.
  • Why it is faster than brute force: right never goes back. Each character enters the set once and leaves once, so the work is at most 2n steps.

In the first approach, we maintain a HashSet<Character> (or boolean[128]) of the characters currently inside s[left .. right]. When right visits ch = s.charAt(right), if ch is already in the set, the window would have a duplicate. So we run while (window.contains(ch)) to remove s.charAt(left) and advance left++ one character at a time until the old copy of ch is evicted. Then we add ch to the set and update maxLen = Math.max(maxLen, right - left + 1).

Predict the output

Run the window by hand

Work out the printed values.

What does this code print?

String s = "pwwkew";
Set<Character> window = new HashSet<>();
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
while (window.contains(s.charAt(right))) {
window.remove(s.charAt(left));
left++;
}
window.add(s.charAt(right));
best = Math.max(best, right - left + 1);
}
System.out.println(best + " " + left);

Jumping with the last-seen index

In the set approach, left steps forward one index at a time until it passes the previous occurrence of ch. Why walk one step at a time when we can jump left directly to lastSeen[ch] + 1?

Example 3 · Optimal: jump left straight past the last repeat with a HashMap (O(n) time, one pass)

LongestSubstringJumpMapDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class LongestSubstringJumpMapDemo {    public static int lengthOfLongestSubstringMap(String s) {        Map<Character, Integer> lastSeen = new HashMap<>();        int left = 0;        int maxLen = 0;
        for (int right = 0; right < s.length(); right++) {            char ch = s.charAt(right);            if (lastSeen.containsKey(ch)) {                left = Math.max(left, lastSeen.get(ch) + 1);            }            lastSeen.put(ch, right);            maxLen = Math.max(maxLen, right - left + 1);        }        return maxLen;    }
    public static void main(String[] args) {        String s = "abba";        System.out.println("Result on abba: " + lengthOfLongestSubstringMap(s));        System.out.println("Result on dvdf: " + lengthOfLongestSubstringMap("dvdf"));    }}
Output
Result on abba: 2
Result on dvdf: 3

What this code does

  • On "abba", when right=3 ('a'), lastSeen.get('a') is 0, while left is already 2. Math.max(2, 0 + 1) keeps left at 2 so the window is "ba" (length 2).
  • On "dvdf", when right=2 ('d'), left jumps to 0 + 1 = 1, forming "vdf" of length 3.
  • Why it is faster than the set version: when a repeat appears, left jumps in one step instead of removing characters one by one, so each index is visited once.

Instead of storing whether ch is in the window, we store the most recent index where ch appeared. When right sees ch again at a previous index prev, we move left to Math.max(left, prev + 1). Why is Math.max(left, ...) critical? Consider s = "abba":

  • right = 0 ('a'): last['a'] = 0, left = 0.
  • right = 1 ('b'): last['b'] = 1, left = 0.
  • right = 2 ('b'): 'b' was seen at 1, so left = Math.max(0, 1 + 1) = 2.
  • right = 3 ('a'): 'a' was last seen at 0, which is before left = 2! Without Math.max(left, ...), setting left = 0 + 1 = 1 would move left backward and include both 'b's at indices 1 and 2!
Never allow left to move backward! Always write left = Math.max(left, lastSeenIndex + 1) because the old occurrence of ch might already be to the left of your current window.

HashMap versus int[128]

To store the last-seen index of each character, you can use a Map<Character, Integer> or a plain int[128] array.

Example 4 · Fastest ASCII solution using int[128] and returning the actual substring

LongestSubstringAsciiDemo.javaJava
import java.util.Arrays;
public class LongestSubstringAsciiDemo {    public static String longestUniqueSubstring(String s) {        int[] lastSeen = new int[128];        Arrays.fill(lastSeen, -1);        int left = 0;        int bestStart = 0;        int maxLen = 0;
        for (int right = 0; right < s.length(); right++) {            char ch = s.charAt(right);            if (lastSeen[ch] >= left) {                left = lastSeen[ch] + 1;            }            lastSeen[ch] = right;            int len = right - left + 1;            if (len > maxLen) {                maxLen = len;                bestStart = left;            }        }        return s.substring(bestStart, bestStart + maxLen);    }
    public static void main(String[] args) {        String sub = longestUniqueSubstring("abcabcbb");        System.out.println("Substring: " + sub + " (length " + sub.length() + ")");    }}
Output
Substring: abc (length 3)

What this code does

  • Checking if (lastSeen[ch] >= left) is equivalent to left = Math.max(left, lastSeen[ch] + 1) because we only jump when the previous occurrence is inside the current window [left .. right].
  • Recording bestStart and maxLen lets us slice s.substring(bestStart, bestStart + maxLen) once at the end instead of creating substrings inside the loop.
  1. Map<Character, Integer>: supports any Unicode character (char or code point), dynamically sizing up to O(min(n, |Σ|)) entries. However, every lookup and update boxes char into Character and computes a hash table probe.
  2. int[128] (initialized to -1 with Arrays.fill(lastSeen, -1)): when the input is standard 7-bit ASCII (English letters, digits, symbols, spaces), a fixed 128-int array uses 512 bytes, performs zero boxing allocations, and turns every lookup into a single array index lastSeen[ch].
  • HashSet / boolean[128] shrinking window: up to 2n character operations (each char added once and removed at most once).
  • HashMap / int[128] jumping window: exactly n iterations, jumping left in O(1) without touching intermediate characters.
  • Use int[128] (and clarify ASCII with your interviewer) for maximum speed and O(1) fixed space.

Next step

Check your understanding

10 quick questions