Cancel out neighbouring pairs
EasyStuck?
Show a hintHide the hint
Keep a stack of surviving letters. If the next letter equals the top, pop instead of pushing.
The ideas behind this problem
Next in this lesson
How long this price has been the bestRepeatedly 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:
abbacahasbbnext to each other. Remove it, leavingaaca.aacanow hasaa, which only became neighbours after thebbwent. Remove it, leavingca.cahas 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.
| letter | top of stack | action | stack |
|---|---|---|---|
| a | empty | push | a |
| b | a | push | ab |
| b | b | equal, pop | a |
| a | a | equal, pop | empty |
| c | empty | push | c |
| a | c | push | ca |
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.