Blind 75 · Sliding Window

Longest Substring Without Repeating Characters

Medium

Watch the walkthrough (5:37)

Problem

The input is a string, s.
A substring is an unbroken run of its characters.
Find the longest substring in which no character repeats.
Return the length of that substring.

Examples

Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: "abc", three characters, no repeats.

Example 2:
Input: s = "bbbbb"
Output: 1

Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: "wke".

Example 4:
Input: s = "dvdf"
Output: 3
Explanation: "vdf" — the second d pushes out only the first d; the v stays in the window.

Constraints

1 <= s.length <= 5 * 10^4
s consists of printable ASCII characters.

Prerequisites

Sliding windows — a left and right edge moving forward only, and the invariant that decides when the left edge advances.
Hash maps or fixed-size counts for what the window currently holds.

How to think about it

1. Sliding Window With a Set

Intuition

A repeat moves the left edge one step past the earlier copy. The window is a run of characters with no repeat, and a set holds exactly the characters in it. Grow the window on the right one character at a time; when the new character is already in the set, its earlier copy is somewhere in the window, so take characters off the left, one at a time, until that copy has gone and the new one fits.

Algorithm

1. Keep a set of the characters in the window, a left edge at 0, and the best length so far.
2. Move the right edge along the string one character at a time.
3. While that character is in the set, take the character at the left edge out of the set and step the left edge forward.
4. Add the character to the set; the window's length is right minus left plus 1, and the best keeps the larger.

Time & Space

Time O(n) — each edge moves forward only, so each character goes into the set once and comes out at most once. Space O(k) for the alphabet in play.

2. Sliding Window With Last-Seen Positions Optimal

Intuition

A window with no repeats stays valid as long as the incoming character is new. When it is not, the left edge must jump to just past that character's PREVIOUS position — not merely one step right. Remembering where each character was last seen makes that jump O(1), and never letting the left edge move backwards is what keeps "abba" honest.

Algorithm

1. Keep a map from character to the index it was last seen at.
2. Extend the right edge one character at a time.
3. If that character was seen at or after the left edge, move left to one past it.
4. Record the character's new position and the window's width.

Time & Space

Time O(n) — each edge moves forward only. Space O(k) for the alphabet in play.