Skip to content
Problem · Canonical Warm-Up
mediumsliding-window · hash-map · two-pointerTime · O(n)Space · O(min(m,n))

Longest Substring Without Repeating Characters

Problem statement

Statement

Given a string s, return the length of the longest substring that contains no repeated character. A substring is contiguous, which is what separates this from the subsequence version.

Examples

s = "abcabcbb"
-> 3                 ("abc"; every longer window repeats a letter)

s = "bbbbb"
-> 1                 ("b")

s = "pwwkew"
-> 3                 ("wke"; note "pwke" is a subsequence, not a substring)

s = ""
-> 0

s = "abba"
-> 2                 ("ab", then "ba"; the trap case for stale indices)

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • s may contain English letters, digits, symbols and spaces, so do not assume lowercase and do not assume 26 characters.

What this problem is really testing

Whether you can maintain an invariant under two competing pressures. The window wants to grow, because a longer window is a better answer. It is forced to shrink whenever growth would break the uniqueness property. Everything in a sliding-window problem comes down to naming the invariant precisely, deciding which pointer restores it, and proving the total work stays linear even though the window moves in both directions.

Think of it as a train with a fixed rule rather than a fixed length: every carriage must carry a different passenger. The front of the train keeps coupling new carriages. The moment a passenger boards who is already somewhere down the train, you uncouple from the back, past the offending carriage, and the rule holds again. Neither end ever reverses. That is why an algorithm whose window is constantly expanding and contracting is still one pass: the two pointers are each monotone, and monotone pointers over n positions do O(n) total work no matter how the window between them oscillates.

The refinement worth reaching in the interview is the jump. A naive shrink walks the left edge forward one character at a time until the duplicate is gone, which can be O(n) per step and O(n^2) overall on inputs such as "abcdefg...zabcdefg...z". If instead you remember where each character was last seen, the left edge can leap directly past the previous occurrence in one move. The upgrade from a set to a map, from "is it here?" to "where was it?", is the actual content of the problem.