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
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public string CollapseDoubles(string 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 C#
public string CollapseDoubles(string typed) {
var kept = new List<char>();
foreach (var ch in typed) {
if (kept.Count > 0 && kept[kept.Count - 1] == ch) kept.RemoveAt(kept.Count - 1);
else kept.Add(ch);
}
return new string(kept.ToArray());
}