Problems › TypeScript › text
Longest stretch with no repeat
A token generator checks its output for the longest run of characters in which nothing appears twice.
- The run has to be a single unbroken stretch, not a selection.
- Every character counts, including spaces and punctuation.
- Empty text has a longest run of zero.
longestUniqueRun(text: string) → int
Where you start
function longestUniqueRun(text: string): number {
}
Worked examples
| Call | Result |
|---|---|
longestUniqueRun("abcabcbb") | 3 |
longestUniqueRun("bbbbb") | 1 |
longestUniqueRun("pwwkew") | 3 |
longestUniqueRun("abcdef") | 6 |
Hint
Slide a window. When a repeat comes in, pull the left edge past where that character was last seen — never backwards.
Reference solution in TypeScript
function longestUniqueRun(text: string): number {
const lastAt = new Map<string, number>();
let best = 0;
let left = 0;
for (let i = 0; i < text.length; i++) {
const c = text[i];
const seen = lastAt.get(c);
if (seen !== undefined && seen >= left) left = seen + 1;
lastAt.set(c, i);
best = Math.max(best, i - left + 1);
}
return best;
}