Boss lesson · Unit 02
No repeats
Longest substring without repeating characters
What you practise
- Last-seen map
- The
abbabug
Try a question from this lesson
Pick one
A window over a string must never hold the same character twice. It holds bac, and the next character is another a. What is the smallest fix that lets the new a in?
Correct answer
Move the left edge to just past the old a
Why
Everything up to and including the old a has to go, which leaves c and then ca. One step right would give aca, still a repeat. Restarting from nothing throws away the c for no reason.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Boss: the longest stretch with no repeats
Find the length of the longest stretch of a string in which no character appears twice.
For abcabcbb the answer is 3 (abc). For bbbb it is 1. Testing every stretch costs O(n²) or worse. A window that grows on the right and jumps forward on the left does it in a single pass.
Concept
Remember where you saw it
Keep a map from each character to the index where it was last seen. If the incoming character was last seen inside the window (prev >= lo), jump the left edge lo to one past that index.
Then record the character's new index and measure the window.
def longest(s):
last = {}
lo = best = 0
for r, ch in enumerate(s):
prev = last.get(ch, -1)
if prev >= lo:
lo = prev + 1
last[ch] = r
best = max(best, r - lo + 1)
return bestfunction longest(s) {
const last = new Map();
let lo = 0, best = 0;
for (let r = 0; r < s.length; r++) {
const prev = last.get(s[r]) ?? -1;
if (prev >= lo) lo = prev + 1;
last.set(s[r], r);
best = Math.max(best, r - lo + 1);
}
return best;
}function longest(s: string): number {
const last = new Map<string, number>();
let lo = 0, best = 0;
for (let r = 0; r < s.length; r++) {
const prev = last.get(s[r]) ?? -1;
if (prev >= lo) lo = prev + 1;
last.set(s[r], r);
best = Math.max(best, r - lo + 1);
}
return best;
}Python notelast.get(ch, -1) returns -1 when the key is missing, where last[ch] would raise KeyError.
JavaScript notelast.get(key) gives undefined for a missing key. ?? -1 swaps in -1 only for undefined or null, so a stored index of 0 survives.
TypeScript noteMap<string, number> says keys are strings and values numbers. get returns number | undefined, and ?? -1 narrows that to a plain number.
9 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.