QuestionsDSA

Longest Substring Without Repeating Characters

Sliding WindowMediumDSA

Given a string, return the length of the longest substring with no repeating characters.

What it tests

Variable-size window: expand right, and shrink left just enough when the invariant breaks.

Approach & answer

Grow a window with `right`. Keep last-seen index of each char. When you hit a repeat inside the window, jump `left` to just past the previous occurrence. The window always holds a valid (unique) substring; track its max length. The subtlety is the `>= left` guard: a duplicate whose last position is behind `left` is already outside the window and must be ignored — otherwise `left` jumps backward and the window corrupts. Jumping left directly (instead of stepping) keeps it O(n) with each pointer only moving forward.

Use this technique when

'Longest/shortest contiguous run satisfying a constraint' → variable window; move left only enough to restore the constraint.

Complexity

Time O(n) · Space O(min(n, alphabet))

References

js