↓Skip to main content
  1. LeetCode/

LeetCode 1047: Remove All Adjacent Duplicates In String

·1 min· ·
LeetCode Easy String Stack
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-30

  • Submissions: Runtime Error → Accepted → Wrong Answer → Runtime Error → Accepted ×3

Approach
#

Interact with the previous character (Stack Template 2): if the stack top equals the current character, pop (both vanish), otherwise push. After a removal the new top becomes “the previous character”, so chained removals happen automatically.

My Attempts
#

Attempt 1 read stack[-1] without checking for emptiness (IndexError). One version added a temp to skip runs of equal characters, removing all three in "aaa": it returned an empty string instead of "a".

Solution
#

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

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Check the stack is non-empty before reading st[-1].
  • Remove one pair at a time: "aaa" leaves "a".

Interview Explanation
#

With a stack, a character equal to the top cancels with it and otherwise is pushed; the new top then meets the next character, handling chains. Time O(n).

Related

LeetCode 1021: Remove Outermost Parentheses
·1 min
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 note: track depth instead of a stack; the ‘(’ raising depth from 0 to 1 and the ‘)’ lowering it from 1 to 0 are outermost, everything else stays
LeetCode 844: Backspace String Compare
·2 mins
LeetCode Easy Two-Pointers String Stack Simulation
LeetCode 844 note: simulate backspaces with a stack; for O(1) space, walk from the end and count how many characters each # skips
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand
LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set
LeetCode 944: Delete Columns to Make Sorted
·1 min
LeetCode Easy Array String Longest-Increasing-Subsequence
LeetCode 944 note: take each column with zip(*strs) and count the columns that are not non-decreasing
LeetCode 953: Verifying an Alien Dictionary
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 953 note: map letters to their alien index and compare each adjacent pair at the first differing character; with no difference, the shorter must come first