Longest Substring Without Repeating Characters

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    Given a string, return the length of the longest substring that contains no repeated character. A substring is a contiguous run of characters, so "pwke" picked from "pwwkew" doesn't count.

    This is the textbook variable-size sliding window: grow the window on the right, and when a rule breaks, move the left edge just far enough to fix it. Original problem: LeetCode 3.

    Example

    In abcabcbb the longest run with no repeat is abc, length 3; adding the next a would repeat it.
    In abcabcbb the longest run with no repeat is abc, length 3; adding the next a would repeat it.
    Input:  "abcabcbb"
    Output: 3        # "abc"
    Input:  "pwwkew"
    Output: 3        # "wke"; "pwke" is not contiguous

    Constraints (assumed)

    • 0 ≤ length ≤ 50,000.
    • Letters, digits, symbols and spaces.

    What this question tests

    • Recognizing a variable-size sliding window ("longest substring such that…").
    • Moving the left edge correctly and only forward.
    • Using a hash map (or a 128-slot array) to remember positions.

    Questions to ask first

    1. What characters can appear? ASCII lets you use an array of 128 instead of a map. (Here: any printable ASCII.)
    2. Length or the substring itself? (Here: the length; returning the substring needs the start index too.)
    3. Is the empty string valid input? (Here: yes, answer 0.)
    4. Case sensitive? (Here: yes, 'a' and 'A' differ.)