Problem 277162 · easy · Phase 02 Linear Data Structures

Collapse Adjacent Pairs

stacks · strings

Given a string s of lowercase letters, repeatedly delete any two adjacent equal letters until no such pair remains. Return the final string (it is the same no matter which pair you delete first).

Examples

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

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

Constraints

  • 0 <= len(s) <= 10**5
  • Target: O(n) time

Goals

  • Use the top of a stack to detect an adjacent duplicate
  • See why one left-to-right pass handles chained removals
Starting Python…