Skip to content
BytePatterns

Longest Unique Substring

Strings: lesson 4 of 11

Grow a window, shrink it the moment a letter repeats.

Lesson 4 of 11 · 5 min

Longest Unique Substring

Step 1 of 10

Find the longest stretch with no repeated character. The right edge only ever moves forward.

The Idea

Keep a window that holds only distinct characters, plus a set of what is inside it. The right edge always advances.

When the incoming character is already in the set, pull the left edge in — dropping characters — until the duplicate is gone. The longest width you ever saw is the answer.

Real-World Example

Streaming deduplication works this way. A telemetry pipeline keeps the longest recent run of distinct device IDs in memory; when an ID repeats, it forgets everything up to the previous sighting instead of rescanning the whole buffer.

The Code

def longest_unique(s):
    seen = set()
    left = best = 0
    for right, ch in enumerate(s):
        while ch in seen:           # shrink until ch is free again
            seen.remove(s[left])
            left += 1
        seen.add(ch)
        best = max(best, right - left + 1)
    return best

print(longest_unique("abcabcbb"))   # 3  -> "abc"
print(longest_unique("bbbbb"))      # 1

Python

Your turn

What does this print?

s = "abba"
seen, left, best = set(), 0, 0
for right, ch in enumerate(s):
  while ch in seen:
      seen.remove(s[left])
      left += 1
  seen.add(ch)
  best = max(best, right - left + 1)
print(best)

Mini quiz

1 / 3

How many times does one character enter and leave the window?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.