Cancelling Beads

Easy · Stack & Monotonic Stack · about 10 min

A toy necklace is a string of lowercase letters, one letter per bead. Whenever two beads with the same letter touch, they both vanish and the beads on either side slide together. This repeats until no two touching beads have the same letter.

Return the final string. The result does not depend on the order in which pairs vanish.

Example: cancelling_beads("abbaca") → "ca" (bb vanishes, then aa, leaving ca)

Example: cancelling_beads("aaa") → "a" (one pair vanishes, one bead is left)

Constraints: 0 to 100,000 beads.

Hints

  • After a pair vanishes, the bead before it meets the bead after it. Which bead do you need to compare with next?
  • Keep the beads that survived so far on a stack. Compare each new bead with the top only.
  • Same letter as the top: pop and drop the new bead. Different: push it. Join the stack at the end.

Learn the pattern first: the Stack & Monotonic Stack lesson.

More Stack & Monotonic Stack problems