Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring that contains no repeating characters.

Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The longest substring without repeating characters is "abc", which has length 3.
Example 2
Input: s = "bbbbb"
Output: 1
Explanation: The longest substring is "b", with length 1.
Example 3
Input: s = "pwwkew"
Output: 3
Explanation: The longest substring is "wke", with length 3.
Constraints:

Contents

Solution - Sliding Window with HashMap

This problem is a classic application of the sliding window technique. We maintain a window defined by two pointers, left and right, that represents the current substring being examined. A HashMap maps each character to its most recent index, which lets us instantly detect duplicates and jump the left pointer past the previous occurrence.

Implementation steps:
Java
public int lengthOfLongestSubstring(String s) {
    Map<Character, Integer> map = new HashMap<>(); // char -> last seen index
    int maxLen = 0;
    int left = 0;

    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);

        // If c was seen before and is within the current window, shrink from left
        if (map.containsKey(c) && map.get(c) >= left) {
            left = map.get(c) + 1;
        }

        map.put(c, right); // update last seen index of c
        maxLen = Math.max(maxLen, right - left + 1);
    }
    return maxLen;
}
Trace through Example 1: s = "abcabcbb"
rightcharleftwindowmaxLen
0a0"a"1
1b0"ab"2
2c0"abc"3
3a1"bca"3
4b2"cab"3
5c3"abc"3
6b5"cb"3
7b7"b"3

Complexity Analysis