Longest unique stretch
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
Given text, find the longest stretch of characters next to each other in which no character appears twice. Return its length.
For example, in banana the longest such stretch is ban, so the answer is 3.
Examples
Example 1
- Input
- text = "banana"
- Output
- 3
"ban" has no repeats. Any longer stretch, like "bana", repeats a letter.
Example 2
- Input
- text = "zzzz"
- Output
- 1
Every stretch longer than one repeats z.
Example 3
- Input
- text = "abcdeafg"
- Output
- 7
"bcdeafg" has no repeats. The whole word doesn't count: it has two a's.
Rules
texthas between 0 and 100,000 characters: letters, digits, spaces and symbols.- Capital and small letters are different characters.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
A stretch means characters next to each other. We want the longest stretch where no character appears twice, and we return its length, not the stretch itself.
2. Solve an example by hand
banana. Start reading: b, ba, ban, then another a, a repeat. The stretch can't include both as, so drop characters from the start until the old a is gone: na. Then another n arrives: drop until the old n is gone, leaving an. Then another a: drop to na. The longest we saw was 3.
The stretch grew at the end and shrank from the start, and it never moved backwards.
3. The slow way
Try every starting position, and extend each one until a character repeats. That's up to n starts × n characters: O(n²) steps. For 100,000 characters with long unique stretches, that's billions.
4. Spot the pattern
The longest stretch of neighbouring items that follows a rule ("no repeats"): a growing and shrinking window. To check the rule instantly, keep the window's characters in a Set.
5. The window idea
For each new character at right:
- If it's already in the window, remove characters from the left, one at a time, until it isn't.
- Add it. The window from
lefttorightnow has no repeats. - Keep the biggest window length.
Grow on the right, shrink on the left
text
- best =
- 1
inWindow (Set)
| character |
|---|
| "b" |
function longestUniqueStretch(text) { const inWindow = new Set(); let left = 0; let best = 0; for (let right = 0; right < text.length; right++) { while (inWindow.has(text[right])) { inWindow.delete(text[left]); left++; } inWindow.add(text[right]); best = Math.max(best, right - left + 1); } return best;}Add "b". The window "b" has no repeats: length 1. A new best!
6. The code, line by line
const inWindow = new Set(); let left = 0; let best = 0;inWindowholds exactly the characters fromlefttoright.bestis the longest valid window so far.for (let right = 0; right < text.length; right++) {rightmoves forward one character at a time.while (inWindow.has(text[right])) { inWindow.delete(text[left]); left++; }While the new character is already in the window, shrink: delete the character at
leftfrom the Set, and movelefton. Awhile, not anif: the copy might be several characters back.inWindow.add(text[right]); best = Math.max(best, right - left + 1);Now it's safe to add the new character. The window holds
right - left + 1characters.
7. How fast is it?
| Every start | Sliding window | |
|---|---|---|
| Time | O(n²) | O(n): each character is added once and removed at most once |
| Extra memory | O(k) | O(k): the Set holds at most one of each different character |
A faster shrink
Instead of removing one character at a time, you can remember where each character was last seen in a Map, and jump left straight past it: left = Math.max(left, lastSeen.get(char) + 1). It's the same O(n), with fewer steps. The Math.max matters: in abba, the last a was seen before the window's start, and left must never move backwards.
Common mistakes
- Using
ifinstead ofwhileto shrink. Inabcb, when the secondbarrives, bothaandbmust leave. - Resetting the window to empty at a repeat. In
abcb, the answercbkeeps thec. Only the characters up to the old copy should go.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Longest unique stretch
Read the 14 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function longestUniqueStretch(text) { const inWindow = new Set(); let left = 0; let best = 0; for (let right = 0; right < text.length; right++) { while (inWindow.has(text[right])) { inWindow.delete(text[left]); left++; } inWindow.add(text[right]); best = Math.max(best, right - left + 1); } return best;}