Algorithms · Sliding window

Longest Substring Without Repeating Characters

The longest piece of text with no letter repeated.

The problem

Return the length of the longest stretch of s (letters side by side) in which no character appears twice. In "abcabcbb" that’s "abc", so 3.

longest_unique("abcabcbb")3
longest_unique("bbbbb")1
Sliding window. Update, don’t recount. A train window: one tree leaves on the left as another arrives on the right.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def longest_unique(s):take some text
best = 0the longest stretch so far
for start in range(len(s)):try every starting letter
seen = set()letters in this stretch
for ch in s[start:]:walk forward from there
if ch in seen:a repeat?
breakthis stretch ends here
seen.add(ch)remember the letter
best = max(best, len(seen))keep the longest
return bestits length

Now ask: what if there were a billion?

Streams of events (clicks, sensor readings, network packets) are checked for repeats the same way: a window that only remembers what’s inside it, so memory stays small however long the stream runs.

Aim for O(n)🔥 boss

Think it through

In “abcda”, you hit the second “a”. Where can the new stretch start?

  • Back at “b”, just after the first “a”
  • At the second “a”, from scratch
Show the answer

Back at “b”, just after the first “a”. “bcd” is still repeat-free. Starting over throws that away. Move the start to just after the earlier copy and keep going.

How do you know where the earlier copy was, without searching?

  • Search back through the window
  • Remember the last position of every letter
Show the answer

Remember the last position of every letter. A dictionary letter → last position answers it in one step. A sliding window plus a dictionary: a pairing that cracks many “longest stretch” puzzles.

Stuck? 3 nudges, smallest first
  1. When you hit a repeat, you don’t need to start over from the next letter. Most of what you’ve seen is still fine.
  2. Keep a window. When a letter repeats inside it, move the window’s start to just after the earlier copy of that letter.
  3. Remember last[ch] = i. If ch was last seen at or after start, set start = last[ch] + 1. The window length is i - start + 1.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def longest_unique(s):take some text
last = {}letter → where we saw it last
start = best = 0the window starts at 0; nothing found yet
for i, ch in enumerate(s):grow the window one letter at a time
if ch in last and last[ch] >= start:is this letter already inside the window?
start = last[ch] + 1jump the start just past its old copy
last[ch] = iremember where we saw it
best = max(best, i - start + 1)is this window a record?
return bestits length

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with sliding window