Problems › JavaScript › 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) {
}
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 JavaScript
function longestUniqueRun(text) {
const lastAt = new Map();
let best = 0, left = 0;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (lastAt.has(c) && lastAt.get(c) >= left) left = lastAt.get(c) + 1;
lastAt.set(c, i);
best = Math.max(best, i - left + 1);
}
return best;
}