CodingNeed.
Mid · Algorithms

Find the longest unique-character window

Return the maximum number of distinct consecutive Unicode code points in the input string.

Examples

Overlapping: "abba" → 2
Typical: "abcabcbb" → 3

Compare approaches

Baseline approach

Grow a fresh set from every possible start. This is straightforward but repeats work.

Time: Expected O(n²) · Space: O(n)

function solve(input) {
 const chars=Array.from(input);let best=0;
 for(let left=0;left<chars.length;left++){
  const seen=new Set();
  for(let right=left;right<chars.length;right++){
   if(seen.has(chars[right]))break;
   seen.add(chars[right]);best=Math.max(best,right-left+1);
  }
 }
 return best;
}
Refined approach

Track the last index at which each character appeared. When a duplicate falls inside the active window, advance the left boundary past its previous occurrence. The boundary must never move backwards. Array.from iterates Unicode code points, so this exercise treats an emoji code point as one item; user-perceived grapheme clusters require a different segmentation policy.

Time: Expected O(n) · Space: O(n), including the code-point array.

function solve(input) {
  const chars = Array.from(input), last = new Map();
  let left = 0, best = 0;
  for (let right=0; right<chars.length; right++) {
    const previous = last.get(chars[right]);
    if (previous !== undefined) left = Math.max(left, previous + 1);
    last.set(chars[right], right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Common traps

  • Using left = previous + 1 unconditionally moves the boundary backwards for abba.
Practise in the workspace →

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.