~/problems / Sliding window

Longest Substring Without Repeating Characters

medium ~25 min

Write length_of_longest_substring(s: str) -> int.

Return the length of the longest contiguous piece of s in which no character appears twice.

Example: "xyzxyzz" gives 3 ("xyz", "yzx", ...). "aaaa" gives 1, "" gives 0. "dvdf" gives 3 ("vdf"); a subsequence such as "dvf" doesn't count, the piece must be contiguous.

Constraints: 0 <= len(s) <= 2 * 10^5; any characters (letters, digits, spaces, symbols).

Aim for O(n); re-checking every substring is too slow for the large test.

Show hint

as you scan, keep the longest repeat-free piece that ends at the current character, and remember where you last saw each character so you know how far its start must move.

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc