Collapse Matching Neighbors
Stacks & QueuesAuto-graded · 21 test casesLast updated
Tests stack-based simulation to eliminate adjacent equal characters iteratively until no more cancellations are possible.
You are given a string s containing any printable characters, including Unicode.
Your task is to repeatedly remove pairs of adjacent identical characters until no such pairs remain. When a pair is removed, the characters on either side become neighbors, which may create a new pair to remove.
Removals proceed from left to right: in "aaa", the leftmost two characters cancel first, leaving "a".
Return the string that remains after all possible removals.
Constraints:
0 ≤ len(s) ≤ 10^6smay contain any printable ASCII or Unicode characters- Your solution must run in
O(n)time wherenis the length ofs - Space complexity should be
O(n)
Examples
Example 1
Input: collapse_matching_neighbors('abbaca')
Output: 'ca'
Example 2
Input: collapse_matching_neighbors('azxxzy')
Output: 'ay'
Example 3
Input: collapse_matching_neighbors('🔥✨✨🔥🚀')
Output: '🚀'
Hints
Hint 1
A stack naturally tracks which character is exposed after each cancellation.
Hint 2
When the top of the stack matches the incoming character, both should be removed.
Hint 3
Use ''.join(stack) at the end rather than concatenating strings in a loop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a stack to maintain the characters that survive after processing each prefix of the input string. As you scan from left to right:
- If the stack is nonempty and its top element equals the current character, you've found an adjacent pair. Pop the top and skip the current character (both cancel).
- Otherwise, push the current character onto the stack.
The stack's top always represents the rightmost surviving character, which is exactly the neighbor that the next input character will meet. This handles cascading cancellations automatically: when you remove a pair, the element beneath is immediately exposed and ready to compare with the next character.
Why It Works
After processing each character, the stack contains the fully reduced form of the prefix scanned so far, with no adjacent duplicates. This invariant holds because:
- When
top == current, removing both is the only cancellation involvingcurrent, and the element beneathtopwas already different fromtop(by induction), so it won't equalcurrent. - When
top != current, pushing creates exactly one new adjacency, which is not a duplicate.
The problem's left-to-right removal convention matches this stack order. Removing matching neighbors in any order always yields the same final string (odd-length runs of identical characters leave one survivor; even-length runs vanish entirely), so the strategy is correct.
Complexity
- Time: O(n). Each character is pushed once and popped at most once. The final join operation is O(n).
- Space: O(n) auxiliary space. In the worst case (no cancellations), all characters remain on the stack.
Implementation
def collapse_matching_neighbors(s: str) -> str:
stack = []
for ch in s:
if stack and stack[-1] == ch:
stack.pop()
else:
stack.append(ch)
return ''.join(stack)
Example walkthrough for "abbaca":
- Read
'a': stack is empty, push →['a'] - Read
'b': top is'a'≠'b', push →['a', 'b'] - Read
'b': top is'b'='b', pop →['a'] - Read
'a': top is'a'='a', pop →[] - Read
'c': stack is empty, push →['c'] - Read
'a': top is'c'≠'a', push →['c', 'a']
Result: "ca"