Problem
Given a string, return the length of the longest substring that contains no repeated character.
Original: LeetCode 3: Longest Substring Without Repeating Characters.
Examples
Example 1
`s = "abcabcbb"``3`Example 2
`s = "bbbbb"``1`Example 3
`s = "pwwkew"``3`Example 4
`s = ""``0`Constraints
0 <= s.length <= 10^5sconsists of English letters, digits, symbols and spaces.
Hints
Hint 1
It is a substring, so the characters must be contiguous. The result is a length, not the substring itself. An empty string has length 0. Repeats that fall to the left of the current window do not count.
Hint 2
A variable-size window whose constraint is 'all characters unique'. The condition is monotonic: growing the window can only introduce a repeat, and shrinking from the left can only remove one.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Check every substring and test uniqueness with a set: O(n²) or worse.
Optimal. A map from character to its last seen index, and a left edge lo. For each hi, if that character was already seen at an index >= lo, move lo to that index + 1. Then store hi as the new last index and update the best length hi - lo + 1.
Alternative. A set plus a while loop that shrinks from the left until the new character is free is the same idea, often a little easier to write, still O(n).
Complexity
- Time
- O(n)
O(n) time, O(min(n, alphabet)) extra space.
- Space
- O(min(n, alphabet)
Code
import java.util.HashMap;
public class LongestSubstringWithoutRepeatingCharacters {
static int lengthOfLongestSubstring(String s) {
var last = new HashMap<Character, Integer>();
int lo = 0, best = 0;
for (int hi = 0; hi < s.length(); hi++) {
var prev = last.put(s.charAt(hi), hi);
if (prev != null && prev >= lo) lo = prev + 1;
best = Math.max(best, hi - lo + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("abcabcbb")); // 3
System.out.println(lengthOfLongestSubstring("bbbbb")); // 1
System.out.println(lengthOfLongestSubstring("pwwkew")); // 3
System.out.println(lengthOfLongestSubstring("")); // 0
}
}Edge cases
- All characters the same, as in "bbbbb", returns 1.
- Repeats that restart the window, as in "pwwkew", whose longest unique substring is "wke" with length 3, not "pwke".
- The empty string returns 0.
Follow-ups
- Longest substring with at most k distinct characters, or Fruit Into Baskets (at most two distinct).
- This problem is regularly named in public Microsoft interview reports.
Interview script
"I grow a window and remember the last index of each character. When the right character is already inside the window, I jump the left edge to one past that earlier index. The longest window I see is the answer. Linear time."
Source: LeetCode 3: Longest Substring Without Repeating Characters Source: Java SE 17 API: HashMap Source: LeetCode Discuss: Microsoft SDE-2 recent questions 2025 (candidate reports, secondary)