Problem 273869 · medium · Phase 02 Linear Data Structures

Bubble Pairs Pop

strings · stacks · transformation

In a bubble game, whenever two equal characters sit next to each other they both pop. Popping can bring two new equal characters together, which then pop as well, and so on until no adjacent pair is equal. Write pop_pairs(s) that returns the final string. Comparison is case-sensitive.

Examples

Input:  s = "abbaca"
Output: "ca"
Explanation: "abbaca" -> "aaca" -> "ca".

Input:  s = "azxxzy"
Output: "ay"

Input:  s = "aaa"
Output: "a"

Constraints

  • 0 <= len(s) <= 10**5, printable ASCII
  • Target: O(n) time; repeatedly calling str.replace is too slow for the largest inputs

Goals

  • Use a stack to handle cascading removals
  • Compare each character with the most recent survivor
  • Avoid repeated rescans of the string
Starting Python…