Cancel Neighboring Letter Pairs in a String
Stacks & QueuesAuto-graded · 23 test casesLast updated
Tests using a stack to repeatedly cancel adjacent equal characters in a string, including cascading cancellations, in linear time.
You are given a string s made of lowercase English letters. Apply the following operation as many times as possible:
- Find two neighboring positions that hold the same letter and delete both of them. The remaining letters close the gap and become neighbors.
Keep going until no two neighboring letters are equal. Return the string that remains.
Removing a pair can bring two other equal letters next to each other, so deletions may cascade. The final string does not depend on which pair you choose to delete first.
If every letter is eventually removed, return the empty string "".
Constraints
0 <= len(s) <= 200000scontains only lowercase English letters (atoz).- The input may be empty, in which case the result is
"". - The solution should run in roughly linear time in
len(s).
Examples
Example 1
Input: cancel_adjacent_pairs('abbaca')
Output: 'ca'
Hints
Hint 1
Rescanning the string after every deletion is too slow for 200,000 characters. Think about processing the string in a single left-to-right pass.
Hint 2
At any moment, only the most recently kept character can cancel with the incoming one. What structure gives you quick access to the latest kept character and lets you remove it?
Hint 3
Use a stack. If the incoming character equals the top, pop the top. Otherwise push the incoming character. Join the stack at the end rather than building the string by repeated concatenation.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process the string from left to right while maintaining a stack that holds the fully reduced form of the part of the string seen so far.
For each character ch:
- If the stack is non-empty and its top equals
ch, the two letters are neighbors and equal, so they cancel. Pop the top and do not pushch. - Otherwise, push
ch.
After the last character, the stack contents (joined in order) are the answer.
Why it is correct
Invariant: after handling the first i characters, the stack is the fully reduced version of that prefix, so it has no two equal neighbors.
When a new character arrives, the only letter it can possibly pair with is the last surviving one, which is the stack top. If they match, removing both leaves the previous reduced prefix, which is again reduced. If they do not match, appending keeps the stack free of equal neighbors. Cascades are handled naturally: after a pop, the new top is compared with the next incoming character.
The final result is also independent of the order in which pairs are removed, so this left-to-right greedy order produces the expected answer.
Complexity
- Time: O(n), since each character is pushed at most once and popped at most once.
- Space: O(n) for the stack.
Using a list and a single join at the end avoids the quadratic cost of repeated string concatenation.
Reference solution
def cancel_adjacent_pairs(s: str) -> str:
stack = []
for ch in s:
if stack and stack[-1] == ch:
stack.pop()
else:
stack.append(ch)
return ''.join(stack)