</>CodexBash
Back to problems
Not started

Cancel out neighbouring pairs

Easy
2000 ms limit256 MB memoryStacks and queuesStrings

Stuck?

Show a hint

Keep a stack of surviving letters. If the next letter equals the top, pop instead of pushing.

Repeatedly remove any two identical letters standing next to each other, until no such pair is left. Return what remains.

Removing a pair can create a new pair, and that one goes too.

Worked example#

For abbaca:

  • abbaca has bb next to each other. Remove it, leaving aaca.
  • aaca now has aa, which only became neighbours after the bb went. Remove it, leaving ca.
  • ca has no pair, so that is the answer.

Doing it in one pass#

Scanning the whole string again after every removal is slow, and the repeated removals are the reason. A stack avoids all of it.

Walk the letters once, keeping a stack of what has survived so far. For each letter, compare it with the top of the stack. Equal means they cancel, so pop instead of pushing. Otherwise push it.

lettertop of stackactionstack
aemptypusha
bapushab
bbequal, popa
aaequal, popempty
cemptypushc
acpushca

The stack holds ca, which is the answer. The cascade is handled for free: after a pop, the next comparison is against whatever was underneath, which is exactly the new neighbour.

Constraints#

  • 1 <= length <= 100000
  • Lowercase letters only
  • The result may be empty, in which case print nothing

Input

s is one word of lowercase letters.

Output

What is left after all removals. May be an empty line.

Examples

Input

abbaca

Output

ca

bb goes first, which puts the two a values together, and they go too.

Input

azxxzy

Output

ay

xx goes, then zz becomes neighbours and goes, leaving ay.

Input

abc

Output

abc

No two neighbours are equal, so nothing is removed.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.