Longest substring without repeating characters


Longest Substring Without Repeating Characters – LeetCode #3


Problem Statement

Given a string s, return the length of the longest substring that contains no duplicate characters.

The substring must consist of contiguous characters, and must not repeat any character.


Examples


Constraints


Intuition

This is a classic Variable Size Sliding Window + Hash Lookup problem.

We are required to find a substring that satisfies a certain condition (no repeated characters), which:

This is a "variable window size with a constraint and a lookup structure" type of problem.


Approach

  1. Use two pointers l (left) and r (right) to define the window.

  2. Use an integer array map (size 128 for all ASCII characters) to count occurrences of characters in the window.

  3. Expand the window (r++):

    • Add the character at s[r] to the map.

    • If it’s a duplicate (map[ch] > 1), shrink the window from the left (l++) until the window has all unique characters again.

  4. At each step, calculate the current window size r - l + 1 and update the result.

  5. Return the maximum window size observed.


Java Code

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int max = Integer.MIN_VALUE;
        int l = 0;
        int[] map = new int[128]; // ASCII character frequency map

        for (int r = 0; r < s.length(); r++) {
            char ch = s.charAt(r);
            map[ch]++;

            // If a character repeats, shrink the window from left
            while (map[ch] > 1) {
                map[s.charAt(l)]--;
                l++;
            }

            max = Math.max(max, r - l + 1);
        }

        // Edge case: empty string
        return max == Integer.MIN_VALUE ? 0 : max;
    }
}

Time and Space Complexity


Dry Run

Input:

s = "abcabcbb"

Steps:

Final max window size with unique characters: "abc"length = 3


Conclusion

This problem is a textbook case of the Variable Size Sliding Window with Lookup (Hash Table) pattern.

It demonstrates:

This same structure can be adapted for: