Skip to the code
cf.
+10 XP

#251 Cancel Matching Neighbors

easy

A word game removes any two equal letters that sit next to each other. Removing a pair can bring two other equal letters together, and they are removed too, until no two neighbors are equal. For example abbaca becomes aaca and then ca.

Write cancelPairs(text) that returns the final string. The result is the same whatever order the pairs are removed in.

Example 1

Input: text = "abbaca"
Output: "ca"

bb goes, which makes aa neighbors, so they go too.

Example 2

Input: text = "azxxzy"
Output: "ay"

xx, then zz are removed.

Constraints

  • 0 <= text.length <= 10^5
  • text has lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).