KatInterview

Collapse Matching Neighbors

Stacks & QueuesAuto-graded · 21 test cases
MediumAuto-gradedStacks & Queuesstackstring-manipulationsimulation

Last 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^6
  • s may contain any printable ASCII or Unicode characters
  • Your solution must run in O(n) time where n is the length of s
  • 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.