Drill

ProblemsJavaScript › patterns

Cancel out the doubled keystrokes

mediumpatternsStacksStringsJavaScript

A faulty keyboard doubles a letter now and then. The cleaner removes any two identical letters sitting next to each other, and keeps going while that leaves a new pair behind.

collapseDoubles(typed: string) → string

Solve it in the editor →

Where you start

function collapseDoubles(typed) {
  
}

Worked examples

CallResult
collapseDoubles("abbaca")"ca"
collapseDoubles("azxxzy")"ay"
collapseDoubles("abc")"abc"
collapseDoubles("aa")""

Hint

Build the result on a stack. For each character, either it cancels the one on top or it goes on top — no rescanning needed.

Reference solution in JavaScript
function collapseDoubles(typed) {
  const kept = [];
  for (const ch of typed) {
    if (kept.length > 0 && kept[kept.length - 1] === ch) kept.pop();
    else kept.push(ch);
  }
  return kept.join("");
}

The same problem in another language

More patterns problems in JavaScript