Skip to content
BytePatterns

Collapse Adjacent Pairs

EasyStacks & Queues#stack#string-scan~15m

Problem

Given a piece of text, repeatedly delete any two neighbouring characters that are identical. Deleting a pair pulls the surrounding characters together, which may create a new neighbouring pair to delete. Keep going until no such pair is left and return what remains.

Examples

Input:  text = "abbaca"
Output: "ca"
Why:    removing bb leaves aaca, and removing aa leaves ca
Input:  text = "azxxzy"
Output: "ay"
Why:    deleting xx creates zz, which then deletes too
Input:  text = "aa"
Output: ""
Why:    edge case, everything cancels and nothing is left

Hints

0 / 3

Stuck on the idea rather than the code? Valid Parentheses covers it.