Skip to main content
13

Longest Substring Without Repeating Characters

Mediumsliding windowhash map

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Sliding WindowRead the beginner guide

Given a string s, return the length of the longest substring that has no repeated characters.

Understand the problem

  • A substring is a piece of the string made of characters that sit next to each other, with nothing skipped. In "pwwkew", "wke" is a substring, but "pwke" is not (it skips a w).
  • No repeated characters means every character inside that piece appears only once.
  • You return only the length, not the substring itself.

Example 1

text
Input:  s = "abcabcbb"
Output: 3

"abc" has no repeats. Any longer piece, like "abca", repeats a letter.

Example 2

text
Input:  s = "bbbbb"
Output: 1

Every piece longer than one character has two bs.

Example 3

text
Input:  s = "pwwkew"
Output: 3

"wke" works. "pwke" would be 4, but it's not a substring because the letters aren't next to each other in s.

Example 4

text
Input:  s = ""
Output: 0

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s contains English letters, digits, symbols and spaces.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Slide a window over the string that never contains a repeated character: grow it on the right, and when a repeat appears, move the left edge just past the earlier copy.

    The naive approach (and why it's slow)

    Check every substring: for every start i and end j, test whether s[i..j] has repeats. There are about n²/2 substrings, and checking each one takes up to n steps, so it's O(n³). Even with a set to check faster, it's still O(n²).

    The key insight

    Most of that work is repeated. If "abc" has no repeats, then when we add the next letter, we only need to ask about that one new letter: is it already in the window?

    So keep one window s[left..right] with a simple rule: no repeats inside.

    • Grow: move right one step, adding a new character.
    • Fix: if that character is already in the window, move left forward until it's not.
    • Record: the window is valid now, so compare its length with the best so far.

    To make the "fix" step instant, remember the last index where each character appeared (a hash map). If the new character was last seen at index p inside the window, the window must start at p + 1.

    Step by step

    s = "abcabcbb":

    rightCharLast seen atInside window?left afterWindowLengthBest
    0aneverno0a11
    1bneverno0ab22
    2cneverno0abc33
    3a0yes1bca33
    4b1yes2cab33
    5c2yes3abc33
    6b4yes5cb23
    7b6yes7b13

    Answer: 3.

    Why max(left, p + 1)? Take s = "abba". At right = 3 (a), the last a was at index 0, but the window already starts at 2 (after the bb fix). That old a is outside the window, so it doesn't matter. Without max, we'd move left back to 1, and the window "bba" would contain two bs.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). right moves through the string once, and left only ever jumps forward.
    • Memory: O(k), where k is the number of different characters (at most the alphabet size).

    Common mistakes

    • Moving left backward. Forgetting the max lets an old, out-of-window sighting drag the window back over a repeat.
    • Updating "last seen" before using it. You need the previous index of the character, so read it first, then store the new index.
    • Off-by-one in the length. A window from left to right (both included) has length right - left + 1.

    Going deeper

    This "grow right, shrink left until valid" loop is the general sliding window template. You'll see the exact same shape in Longest Repeating Character Replacement and Minimum Window Substring, just with a different rule for "valid".

    Reference solution

    js
    /**
     * @param {string} s
     * @return {number}
     */
    export default function lengthOfLongestSubstring(s) {
      // character -> the last index where we saw it
      const lastSeen = new Map()
      let left = 0 // the window is s[left..right], with no repeats inside
      let best = 0
      for (let right = 0; right < s.length; right++) {
        // Read the previous sighting BEFORE storing the new one.
        const previous = lastSeen.get(s[right])
        // A repeat inside the window: start the window just after the old copy.
        // max() ignores old sightings from before the window, so left never moves back.
        if (previous !== undefined) left = Math.max(left, previous + 1)
        lastSeen.set(s[right], right)
        best = Math.max(best, right - left + 1) // window length, both ends included
      }
      return best
    }
    ts
    export default function lengthOfLongestSubstring(s: string): number {
      // character -> the last index where we saw it
      const lastSeen = new Map<string, number>()
      let left = 0 // the window is s[left..right], with no repeats inside
      let best = 0
      for (let right = 0; right < s.length; right++) {
        // Read the previous sighting BEFORE storing the new one.
        const previous = lastSeen.get(s[right])
        // A repeat inside the window: start the window just after the old copy.
        // max() ignores old sightings from before the window, so left never moves back.
        if (previous !== undefined) left = Math.max(left, previous + 1)
        lastSeen.set(s[right], right)
        best = Math.max(best, right - left + 1) // window length, both ends included
      }
      return best
    }
    python
    def length_of_longest_substring(s: str) -> int:
        # character -> the last index where we saw it
        last_seen = {}
        left = 0  # the window is s[left..right], with no repeats inside
        best = 0
        for right, char in enumerate(s):
            # A repeat inside the window: start the window just after the old copy.
            # max() ignores old sightings from before the window, so left never moves back.
            if char in last_seen:
                left = max(left, last_seen[char] + 1)
            last_seen[char] = right
            best = max(best, right - left + 1)  # window length, both ends included
        return best