Drill

ProblemsJavaScript › text

Longest stretch with no repeat

hardtextJavaScript

A token generator checks its output for the longest run of characters in which nothing appears twice.

longestUniqueRun(text: string) → int

Solve it in the editor →

Where you start

function longestUniqueRun(text) {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More text problems in JavaScript