Length 1:13Loading the video
Loading the video
Find the longest run of letters where nothing repeats. Slide a window along the string and keep a map of where each letter was last seen, so one pass is enough.
Narrated by an AI voice.
This is LeetCode problem three.
Given a string, find the length of the longest substring with no repeated characters.
Take the string pwwkew.
A substring is a run of letters that sit next to each other.
The run wke has no repeats, so the answer is three.
One way is to check every substring for repeats.
That work grows like n squared or worse, which is slow for long strings.
A faster idea is a sliding window.
We keep a left edge and a right edge.
The right edge moves forward one letter at a time.
When a letter repeats, the left edge jumps past its earlier copy.
To jump quickly, we keep a map.
It stores the last position where we saw each letter.
Positions count from zero.
At position zero, p is new.
At one, w is new, so the length is two.
At two, w repeats.
It was last seen at one, so left moves to two.
Then k and e are new, so the best length becomes three.
At five, w repeats.
It was last seen at two, so left moves to three.
Here is the JavaScript.
We create the map, with left and best at zero.
Right moves across the string.
If the letter was seen inside the window, left jumps past it.
We save its position and update best.
Then we return best.
The map can hold old positions left of the window.
In abba, the last a was seen at zero, but left is at two.
The check against left ignores it, so left never moves backward.
Each letter is visited once, so the time grows in step with the string length.
The map holds one entry per distinct letter, so extra memory depends on the alphabet.
Map lookups take constant time on average.
A sliding window with a map of last positions finds the longest substring without repeats in one pass.
Sliding window: how it works and when to use it
A sliding window keeps a run of neighbors and moves it along the input, so each item is handled once. Signals, a worked example, code and practice.
Type any algorithm, interview problem or system, and get your own narrated video.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video