File: remove-all-adjacent-duplicates-in-string/solution.py

Date: 2026-06-06

Time: 18:44

Purpose

This file solves LeetCode 1047 — Remove All Adjacent Duplicates In String. It owns the Solution.removeDuplicates method, which repeatedly removes pairs of adjacent identical characters until no more exist. For example, "abbaca" becomes "ca": abba, then aacaca.

Key Components

Solution.removeDuplicates(s: str) -> str — The sole method. Takes a string of lowercase English letters and returns the string after all adjacent duplicate pair removals have been applied. The removal is transitive: removing a pair may create a new adjacent pair, which is also removed.

Patterns

Stack-based simulation. Rather than repeatedly scanning the string for pairs (which would be O(n²)), this uses a stack to process each character exactly once. The stack acts as the "result so far" — when the next character matches the top, they cancel out (pop); otherwise it extends the result (push). This is the textbook idiom for adjacent-pair cancellation problems.

The final "".join(stack) converts the list-of-characters back into a string.

Dependencies

Imports: None — pure standard library, no external dependencies.

Imported by: The test_solution.py in the same directory. The long "Imported By" list in the prompt is misleading — those are unrelated test files in sibling problem directories; they import their own local solution.py, not this one.

Flow

1. Initialize an empty stack (list[str]).

2. Iterate through each character ch in the input string s.

3. If the stack is non-empty and its top element equals ch, pop the top (the pair cancels).

4. Otherwise, push ch onto the stack.

5. After all characters are processed, join the stack into a string and return it.

For "abbaca":

Invariants

Error Handling

None. Empty input produces an empty string naturally (the loop body never executes, "".join([]) returns ""). No exceptions are raised or caught.

Topics to Explore

Beliefs