Full answer
The brute force approach checks every substring, which is O(n cubed) with a naive uniqueness check and O(n squared) at best. A sliding window does it in one pass.
Idea: keep a window [left, right] that never contains a repeated character. Move right forward. If the new character appeared before at index last and that index is inside the window (last >= left), a repeat would occur, so set left = last + 1. Record the current character's index in a Map. After each step, the window length is right - left + 1, and the answer is the maximum of those lengths.
Why it is O(n): right visits every position once, and left only moves forward, never back. Each map operation is O(1) on average. Space is O(k), where k is the size of the alphabet or the number of different characters in the window.
The check last >= left is the subtle part. The map may hold an old index that is already outside the window. Without that check, left could move backward and give wrong answers, for example on "abba": when the second a is read, its last index 0 is smaller than left (which moved to 2 after the second b), so it must be ignored.
Variations: return the substring itself (store the start index of the best window), or limit to at most k distinct characters (use a count Map and shrink the window while there are too many keys). The same window pattern solves many "longest or shortest range with a condition" problems.
Unicode: iterating by index uses UTF-16 code units, so for emoji use [...text].
function longestUnique(text) {
const lastSeen = new Map();
let left = 0;
let best = { length: 0, start: 0 };
const chars = [...text];
chars.forEach((ch, right) => {
if (lastSeen.has(ch) && lastSeen.get(ch) >= left) left = lastSeen.get(ch) + 1;
lastSeen.set(ch, right);
if (right - left + 1 > best.length) best = { length: right - left + 1, start: left };
});
return { length: best.length, text: chars.slice(best.start, best.start + best.length).join('') };
}
function longestAtMostKDistinct(text, k) {
const counts = new Map();
let left = 0;
let best = 0;
for (let right = 0; right < text.length; right++) {
counts.set(text[right], (counts.get(text[right]) ?? 0) + 1);
while (counts.size > k) {
const ch = text[left++];
counts.set(ch, counts.get(ch) - 1);
if (counts.get(ch) === 0) counts.delete(ch);
}
best = Math.max(best, right - left + 1);
}
return best;
}
for (const input of ['abcabcbb', 'bbbbb', 'pwwkew', 'abba', '', 'dvdf']) {
console.log(JSON.stringify(input), longestUnique(input));
}
console.log(longestAtMostKDistinct('eceba', 2), longestAtMostKDistinct('aaaa', 1), longestAtMostKDistinct('abc', 0));Run with Node.js v24.22.1 as js-113.js; two runs gave identical output. Output: "abcabcbb" { length: 3, text: 'abc' } "bbbbb" { length: 1, text: 'b' } "pwwkew" { length: 3, text: 'wke' } "abba" { length: 2, text: 'ab' } "" { length: 0, text: '' } "dvdf" { length: 3, text: 'vdf' } 3 4 0
Key points
- Sliding window with left and right pointers, plus a Map of last seen indexes.
- On a repeat inside the window, move left to last index plus one.
- Always check that the last index is at least left; "abba" shows why.
- O(n) time because both pointers only move forward; O(k) space.
- The pattern extends to at most k distinct characters and similar window problems.
Common mistakes
- Moving left back to an old index because the left check is missing.
- Resetting the whole window on a repeat, which makes the solution O(n squared).
- Confusing substring (contiguous) with subsequence.
- Returning the start index of the window as its length.
Follow-ups
- How would you return the substring and not only its length?
- How does the solution change for at most k distinct characters?
- What changes if the input is a very long stream you cannot index into?
Tips
- Draw the window on "abba" and show why the left check is needed.
- State why the pointers give O(n).
- Name the pattern: sliding window with a hash map.