Repaso
Español
Algorithms & DSIntermediateALG-12

Longest substring without repeating characters. Optimal technique and complexity?

Options

  1. Brute force over all substrings, O(n³)
  2. Sliding window with a last-seen map, O(n) (Correct option)
  3. Sort the characters first, O(n log n)
  4. A DP table over all substring pairs, O(n²)

Answer

Sliding window with a last-seen map, O(n)

Why

A sliding window is a range [left, right] over the string that you grow and shrink instead of restarting.

Move right forward one character at a time. If that character already appears inside the window, move left just past its previous position. Track the best window length.

Each pointer only moves forward, so the total work is O(n).

Remember

Best contiguous substring/subarray → sliding window.

Key terms

Practice this question in Repaso