Drill

ProblemsPython › patterns

Cancel out the doubled keystrokes

mediumpatternsStacksStringsPython

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.

collapse_doubles(typed: string) → string

Solve it in the editor →

Where you start

def collapse_doubles(typed: str) -> str:
    

Worked examples

CallResult
collapse_doubles("abbaca")"ca"
collapse_doubles("azxxzy")"ay"
collapse_doubles("abc")"abc"
collapse_doubles("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 Python
def collapse_doubles(typed: str) -> str:
    kept = []
    for ch in typed:
        if kept and kept[-1] == ch:
            kept.pop()
        else:
            kept.append(ch)
    return "".join(kept)

The same problem in another language

More patterns problems in Python