Emmanuel Akinfulubi

JavaScriptString

Longest substring without repeats in JavaScript

Advanced ยท 4 min read

In 'abcabcbb', what is the longest stretch of characters with no letter repeated? abc. In 'pwwkew' it is wke. This is one of the best-known interview questions, and it is the classic way to learn the sliding window, a technique you will use again for "longest run", "best streak" and "busiest hour" problems.

In this tutorial you will build longestUnique in one pass over the string, using a Map to remember where each character was last seen. You will also meet the two inputs that break the obvious first attempts. You should know for loops, slice and the basics of a Map (get, set, has). The window idea is explained from zero.

The sliding window

Picture a window over the string with a left edge, start, and a right edge, i. The characters inside the window never repeat.

  • Move the right edge forward one character at a time.
  • If the new character is already inside the window, move the left edge to just past its earlier copy. Now the window has no repeats again.
  • After each move, if the window is the longest seen so far, remember it.

Both edges only ever move forward. That is what makes it fast: one pass, no going back.

Remembering where we saw each character

A Map stores pairs of key and value. Here the key is a character and the value is the index where we last saw it:

JavaScript

const lastSeen = new Map();
lastSeen.set('a', 0);
console.log(lastSeen.get('a')); // 0
console.log(lastSeen.has('b')); // false

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

54 Longest substring without repeating characters

hard

Find the longest run of characters in a string with no repeats. 'abcabcbb' gives 'abc'; 'pwwkew' gives 'wke'.

Stuck? Three hints, smallest first
  1. 1. Keep a window with a start and an end, and remember where each character was last seen.
  2. 2. On a repeat, move the start to just after the previous sighting, and never backwards.
  3. 3. The >= start check is what stops a stale index from dragging the window back.

Step 1: the first wrong turn, restarting from scratch

A natural first idea is "when you hit a repeat, start a new window at the repeat". Try it on 'dvdf'. The answer should be vdf.

Step 1

function restartAtRepeat(text) {
  let window = '';
  let best = '';
  for (const c of text) {
    if (window.includes(c)) window = '';
    window += c;
    if (window.length > best.length) best = window;
  }
  return best;
}
console.log(restartAtRepeat('dvdf')); // 'dv'

At the second d, the window dv is thrown away completely. But v didn't need to go. Only the first d did. Throwing the whole window away loses vdf.

Step 2: move the start just past the repeat

The fix is to move the left edge to one place after the earlier copy, keeping everything after it:

Step 2

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

i - start + 1 is the window's length. 'dvdf' now works. But 'tmmzuxt' gives mmzuxt, which has the letter m twice. Something is still wrong.

Step 3: never move the start backwards

Walk through 'tmmzuxt'. At the second m (index 2), start moves to 2. Good. At the last t (index 6), the map says t was last seen at index 0, so start is set to 1, backwards, back over the repeated m. The window mmzuxt now holds two ms.

That old t was already outside the window. The fix is to move the start only when the earlier copy is inside the window, meaning its index is at least start:

Step 3

function longestUnique(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = '';
  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 = text.slice(start, i + 1);
  }
  return best;
}
console.log(longestUnique('tmmzuxt')); // 'mzuxt'
console.log(longestUnique('dvdf'));    // 'vdf'

lastSeen.get(c) >= start is the most important check in the whole function. It ignores old sightings the window has already left behind.

Step 4: the classic examples

Step 4

function longestUnique(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = '';
  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 = text.slice(start, i + 1);
  }
  return best;
}
console.log(longestUnique('abcabcbb')); // 'abc'
console.log(longestUnique('bbbbb'));    // 'b'
console.log(longestUnique('pwwkew'));   // 'wke'
console.log(longestUnique('abcdef'));   // 'abcdef'
console.log(JSON.stringify(longestUnique(''))); // ""

With 'pwwkew', the second w moves the start to index 2, and the window grows to wke before the last w pushes it on again. An empty string never enters the loop, so best stays ''.

Step 5: emoji and code units

text[i] reads one code unit, one of the small pieces JavaScript stores strings in. Most emoji take two:

Step 5

function longestUnique(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = '';
  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 = text.slice(start, i + 1);
  }
  return best;
}
console.log(longestUnique('๐Ÿ‘๐Ÿ‘').length);      // 2
console.log([...longestUnique('๐Ÿ‘๐Ÿ‘')].length); // 1

The answer is one emoji, but its length is 2. For text with emoji, spread it into an array first, [...text], and run the same loop over the array.

The full solution

The panel has longestUnique and prints the answer for six strings, including 'dvdf' and 'tmmzuxt'. Press Run, then read the checks underneath.

The answer

function longestUnique(text) {
  const lastSeen = new Map();
  let start = 0;
  let best = '';

  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    // Only move the start if the previous sighting is inside the window.
    if (lastSeen.has(c) && lastSeen.get(c) >= start) start = lastSeen.get(c) + 1;
    lastSeen.set(c, i);
    if (i - start + 1 > best.length) best = text.slice(start, i + 1);
  }
  return best;
}

for (const t of ['abcabcbb', 'bbbbb', 'pwwkew', 'dvdf', 'tmmzuxt', 'abcdef']) {
  console.log(t.padEnd(10), '->', longestUnique(t));
}

Output


      
10 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 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('the classic example', longestUnique('abcabcbb'), 'abc');
test('all the same character gives one', longestUnique('bbbbb'), 'b');
test('the window moves past the repeat rather than restarting', longestUnique('pwwkew'), 'wke');
test('a string with no repeats is its own answer', longestUnique('abcdef'), 'abcdef');
test('an empty string gives an empty answer', longestUnique(''), '');
test('the case that catches a naive reset to zero', longestUnique('dvdf'), 'vdf');
test('and the one that catches a stale index', longestUnique('tmmzuxt'), 'mzuxt');
test('the answer never contains a repeat', new Set(longestUnique('tmmzuxt')).size, longestUnique('tmmzuxt').length);
test('the window works in code units, so its length is not a character count', longestUnique('๐Ÿ‘๐Ÿ‘').length, 2);
test('while the answer itself is one character', [...longestUnique('๐Ÿ‘๐Ÿ‘')].length, 1);

The lastSeen.get(c) >= start guard is the whole exercise. Without it, 'dvdf' moves the start back to 1 when it meets the second d, then the f is measured against a window that has already been left behind. Both 'dvdf' and 'tmmzuxt' are in the assertions because they fail different naive versions.

It is O(n) with one pass and one map, which is the point of a sliding window: the start only ever moves forward, so no character is examined more than twice.

Indexing with text[i] means the window counts code units. For text with emoji, run it over [...text] and track array indexes instead.

Common mistakes

  • Restarting the window at a repeat. You lose the characters after the earlier copy. Move the start to just past it instead.
  • Moving the start backwards. Without >= start, an old sighting drags the window back. Only move forward.
  • Finding the earlier copy with indexOf. It returns the first copy in the whole string, not the latest one. Keep a map of last positions.

Try it yourself

  1. Change the function to return only the length, without building the substring.
  2. Run it over [...text] so '๐Ÿ‘a๐Ÿ‘' gives '๐Ÿ‘a'.
  3. Return the start index as well as the substring, so 'pwwkew' gives { start: 2, text: 'wke' }.

Keep practising

Newsletter

New writing, when it lands.

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