DSA AnimatorREVISION VIDEOS
← Back to problems
New

Longest Substring Without Repeating Characters — LeetCode 3 video explanation

You get a string. Return the length of the longest substring where no character repeats. A substring is a run of consecutive characters, with nothing skipped.

Loading videos…

DSA Animator › DSA Revision › Strings › Longest Substring Without Repeating Characters

Key moments in the Longest Substring Without Repeating Characters video

0:05Problem0:14Example0:25Brute force0:33Key idea0:50Dry run1:22Code1:42Takeaway

What you will learn

Remember: a window plus a last-seen map lets left jump, never step back. Only jump when the repeat is inside the current window. The video solves Longest Substring Without Repeating Characters (LeetCode 3, Medium) with the Sliding Window pattern from the Strings topic, and you can replay every step in the interactive Longest Substring Without Repeating Characters animation.

Longest Substring Without Repeating Characters video transcript

Problem

You get a string. Return the length of the longest substring where no character repeats. A substring is a run of consecutive characters, with nothing skipped.

Example

In p w w k e w, the longest such substring is w k e. Its length is 3. Note that p w k e is not a substring, because it skips a character.

Brute force

Checking every substring is O of n cubed. Even a smarter check is still O of n squared. That is too slow for long strings.

Key idea

Keep a sliding window, from left to right. Right moves forward one character at a time. A hash map remembers the last index of every character. If the new character already appears inside the window, jump left to just after its previous index. At each step, update the best with the window length.

Dry run

Right at 0 is p, which is new, so the window length is 1. Right at 1 is w, new, so the length is 2. Right at 2 is w again. w was last seen at index 1, which is inside the window. So left jumps to index 2, and the window is just w. Right at 3 is k, new, so the length is 2. Right at 4 is e, new, so the length is 3, a new best. Right at 5 is w, last seen at index 2. Left moves to index 3, and the window k e w has length 3. The string ends, and the answer is 3.

Code

In code, keep a map, left at 0, and best at 0. For each right, if the character is in the map at an index of at least left, move left just past it. Then record the character at right, and update the best. Each character is visited once, so time is O of n. Space is O of k, where k is the number of distinct characters.

Takeaway

Remember: a window plus a last-seen map lets left jump, never step back. Only jump when the repeat is inside the current window.

More Strings revision videos

← All 185 DSA revision videos