Emmanuel Akinfulubi

JavaScriptFunction

Longest non-repeating substring in JavaScript

Advanced · 4 min read

In 'abcabcbb', what is the longest stretch of characters where none of them repeats? It is 'abc'. This puzzle is one of the best-known coding interview questions, and the method behind it, the sliding window, solves a whole family of "longest run" and "best stretch" problems in streams of data.

In this tutorial you will write longestUnique(text). You will build a slow version you can trust first, then the fast sliding window, and meet the two test strings that catch the usual bugs. You need to know loops, strings and functions. A Map is used to remember positions, and it is explained as we go.

What counts as a substring

A substring is a piece of the string with no gaps: 'bca' is a substring of 'abcabcbb', but 'acb' is not, because you can't skip characters. slice(start, end) cuts one out, from start up to but not including end:

JavaScript

console.log('abcabcbb'.slice(1, 4)); // 'bca'

So the task is: of all the substrings with no repeated character, return the longest.

A Set spots repeats

A Set holds each value once. Build one from a string and its size is the number of different characters. If that equals the length, nothing repeats:

JavaScript

console.log(new Set('abc').size);  // 3: same as the length, no repeats
console.log(new Set('abca').size); // 3: length is 4, so something repeats

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

26 Longest substring without repeating characters

hard

Find the longest run in a string where no character repeats.

Stuck? Three hints, smallest first
  1. 1. A sliding window: grow the right edge, and pull the left edge in when a repeat appears.
  2. 2. Remember the last index of each character so the left edge can jump, not creep.
  3. 3. The left edge must never move backwards, or the window becomes invalid.

Step 1: a slow version you can trust

The simplest idea: try every substring, keep the longest one with no repeats.

Step 1

function longestUniqueBrute(text) {
  let best = '';
  for (let i = 0; i < text.length; i++) {
    for (let j = i + 1; j <= text.length; j++) {
      const piece = text.slice(i, j);
      if (new Set(piece).size === piece.length && piece.length > best.length) best = piece;
    }
  }
  return best;
}
console.log(longestUniqueBrute('abcabcbb')); // 'abc'
console.log(longestUniqueBrute('pwwkew'));   // 'wke'

This is correct, but slow: a string ten times longer takes about a thousand times as long. It is still useful. Later you can check the fast version against it.

Step 2: the sliding window idea

Picture a window over the string with a left edge and a right edge. Everything inside has no repeats.

  • Move the right edge one character at a time.
  • If the new character is already inside the window, move the left edge to just past the earlier copy.
  • After each move, check whether the window is the longest so far.

Each character is looked at once, so the work grows in step with the length of the string.

Step 3: remember where each character was

To move the left edge straight to the right place, you need the last position of each character. A Map stores that: the key is the character, the value is its latest index.

Step 3

const lastSeen = new Map();
lastSeen.set('a', 0);
lastSeen.set('a', 3);            // a later 'a' replaces the old position
console.log(lastSeen.get('a'));  // 3
console.log(lastSeen.has('z'));  // false

Step 4: the natural wrong turn

A first attempt often restarts the window at the repeated character, throwing away everything before it:

Step 4

function restartAtRepeat(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = '';
  for (let i = 0; i < text.length; i++) {
    if (lastSeen.has(text[i]) && lastSeen.get(text[i]) >= start) start = i;
    lastSeen.set(text[i], i);
    if (i - start + 1 > best.length) best = text.slice(start, i + 1);
  }
  return best;
}
console.log(restartAtRepeat('dvdf')); // 'dv', but the answer is 'vdf'

When the second d arrives, this version throws away v too. But v was fine. Only the first d had to go. The left edge should land one past the earlier d, at index 1, which keeps 'vd' and then grows to 'vdf'.

Step 5: the guard that stops the edge going back

Now set start = lastSeen.get(c) + 1. There is one more catch, shown by 'tmmzuxt'. Without a check, an old position can drag the left edge backwards:

Step 5

function noGuard(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = '';
  for (let i = 0; i < text.length; i++) {
    if (lastSeen.has(text[i])) start = lastSeen.get(text[i]) + 1;
    lastSeen.set(text[i], i);
    if (i - start + 1 > best.length) best = text.slice(start, i + 1);
  }
  return best;
}
console.log(noGuard('tmmzuxt')); // 'mmzuxt', which repeats 'm'

The last t was first seen at index 0. By then the window starts at index 2, so that old t is already outside it. Jumping to index 1 moves the edge back and lets the two ms in. The fix is to only move when the earlier copy is inside the window: lastSeen.get(c) >= start.

Step 6: the finished function

Put it together. Instead of slicing a new string every time the window grows, the answer stores the best window's start and length, and slices once at the end:

Step 6

function longestUnique(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = { start: 0, length: 0 };
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (lastSeen.has(c) && lastSeen.get(c) >= start) {
      start = lastSeen.get(c) + 1;
    }
    lastSeen.set(c, i);
    if (i - start + 1 > best.length) best = { start, length: i - start + 1 };
  }
  return text.slice(best.start, best.start + best.length);
}
console.log(longestUnique('dvdf'));    // 'vdf'
console.log(longestUnique('tmmzuxt')); // 'mzuxt'
console.log(longestUnique('bbbbb'));   // 'b'
console.log(longestUnique(''));        // ''
console.log(['abcabcbb', 'pwwkew', 'dvdf', 'tmmzuxt'].every(
  (t) => longestUnique(t).length === longestUniqueBrute(t).length)); // true

i - start + 1 is the window's length. The last line checks the fast version against the slow one from Step 1. The two share no logic, so agreement is good evidence.

The full solution

The panel has longestUnique and the brute-force check. It prints the answer and its length for nine test strings, including 'dvdf' and 'tmmzuxt'. Press Run to see the output.

The answer

/* Sliding window in one pass. lastSeen holds the most recent index of each
   character, so when a repeat turns up the left edge jumps straight past it. */
function longestUnique(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = { start: 0, length: 0 };

  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (lastSeen.has(c) && lastSeen.get(c) >= start) {
      start = lastSeen.get(c) + 1;          // >= start: never move the edge back
    }
    lastSeen.set(c, i);
    if (i - start + 1 > best.length) best = { start, length: i - start + 1 };
  }
  return text.slice(best.start, best.start + best.length);
}

// Brute force, as an independent check. O(n^3), fine for short strings.
function longestUniqueBrute(text) {
  let best = '';
  for (let i = 0; i < text.length; i++) {
    for (let j = i + 1; j <= text.length; j++) {
      const piece = text.slice(i, j);
      if (new Set(piece).size === piece.length && piece.length > best.length) best = piece;
    }
  }
  return best;
}

const cases = ['abcabcbb', 'bbbbb', 'pwwkew', 'abcdef', '', 'a', 'au', 'dvdf', 'tmmzuxt'];

for (const t of cases) {
  console.log(JSON.stringify(t).padEnd(11), '->', JSON.stringify(longestUnique(t)), 'length', longestUnique(t).length);
}
console.log("--- 'dvdf' is the case that catches a creeping left edge ---");
console.log("the answer is 'vdf', length 3, not 'df'");
console.log("--- 'tmmzuxt' needs the >= start guard ---");
console.log("without it the final t would drag the edge back to index 1");

Output


      
16 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 16 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

16 checks

test("'abcabcbb' gives abc", longestUnique('abcabcbb'), 'abc');
test('all the same gives one character', longestUnique('bbbbb'), 'b');
test("'pwwkew' gives wke", longestUnique('pwwkew'), 'wke');
test('no repeats gives the whole string', longestUnique('abcdef'), 'abcdef');
test('an empty string gives an empty string', longestUnique(''), '');
test('one character', longestUnique('a'), 'a');
test('two different characters', longestUnique('au'), 'au');
test("'dvdf' gives vdf, not df", longestUnique('dvdf'), 'vdf');
test("'tmmzuxt' gives mzuxt", longestUnique('tmmzuxt'), 'mzuxt');
test('the brute-force version agrees on every case', cases.every((t) => longestUnique(t).length === longestUniqueBrute(t).length), true);
test('the result really has no repeats', new Set(longestUnique('abcabcbb')).size, longestUnique('abcabcbb').length);
test('and that holds for every case', cases.every((t) => { const r = longestUnique(t); return new Set(r).size === r.length; }), true);
test('the result is a contiguous slice of the input', cases.every((t) => t.includes(longestUnique(t))), true);
test('spaces count as characters', longestUnique('a b a'), 'a b');
test('it is case-sensitive', longestUnique('aA'), 'aA');
test('a long run is found', longestUnique('ab' + 'cdefghij' + 'ab'), 'abcdefghij');

The sliding window is the technique: one pass, with two edges. The right edge always advances; the left edge jumps to just past the previous occurrence of whatever repeated. Remembering the last index of each character is what allows the jump — moving the left edge one step at a time would make this O(n²).

Two test strings earn their place. 'dvdf' catches a version whose left edge creeps instead of jumping — the answer is 'vdf'. And 'tmmzuxt' is why the condition is lastSeen.get(c) >= start and not just lastSeen.has(c): the final t was last seen at index 0, which is already behind the window, so without the guard the left edge would be dragged backwards and the window would contain a repeat.

Cross-checking against a brute-force version on every case is the cheap way to be confident, since the two share no reasoning at all.

Common mistakes

  • Restarting the window at the repeat. Move the left edge to one past the earlier copy, not to the current position, or 'dvdf' gives 'dv'.
  • Letting the left edge move backwards. Only jump when the earlier copy is inside the window (>= start). 'tmmzuxt' catches this.
  • Mixing up substrings and subsequences. A substring has no gaps. Picking characters from here and there is a different problem.

Try it yourself

  1. Return the length only, and check that 'pwwkew' gives 3.
  2. Make the function ignore case, so 'aA' counts as a repeat and gives 'a'.
  3. Return the start position as well as the text, like { start: 2, text: 'wke' } for 'pwwkew'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.