Problems › JavaScript › patterns
Cancel out the doubled keystrokes
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.
- Two identical characters next to each other both disappear.
- Removing a pair can bring two more together, and those go too.
- Keep going until no adjacent pair is left.
- Text with nothing to remove comes back unchanged.
collapseDoubles(typed: string) → string
Where you start
function collapseDoubles(typed) {
}
Worked examples
| Call | Result |
|---|---|
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("");
}