SDE & MLE Prep

1047. Remove All Adjacent Duplicates In String

Problem

Repeatedly delete two adjacent equal letters from s until no such pair remains, and return the final string (it is unique).

Example: "abbaca" → "ca"

Use the output as a stack: if the incoming char equals the top, pop; else push.

Complexity: O(n).

class Solution:
    def removeDuplicates(self, s: str) -> str:
        st = []
        for ch in s:
            if st and st[-1] == ch:
                st.pop()
            else:
                st.append(ch)
        return "".join(st)