1047. Remove All Adjacent Duplicates In String

6 min read

Removing all adjacent duplicates in a string is a common algorithmic challenge that appears in coding interviews, data cleaning tasks, and text processing applications. On the flip side, in this article we will explore how to remove all adjacent duplicates in string efficiently, discuss the underlying logic, provide a clear step‑by‑step implementation, and answer frequently asked questions. By the end of the guide you will have a solid understanding of the technique and be able to apply it to real‑world problems Easy to understand, harder to ignore. No workaround needed..

Understanding the Problem

Understanding the Problem

At first glance, "removing adjacent duplicates" can mean two slightly different things, and it helps to be explicit about which one you are solving. The most common interview version works like this:

You are given a string of lowercase letters. A duplicate removal picks two adjacent, equal characters and deletes both. You repeat this process until no more removals are possible, then return the resulting string.

Take the string "abbaca":

  1. Remove the adjacent "bb" → "aaca"
  2. Remove the adjacent "aa" → "ca"
  3. No adjacent duplicates remain, so the answer is "ca".

The key insight is that removals can create new adjacencies. When you delete "bb", the two "a" characters on either side suddenly become neighbors and must be removed too. This cascading behavior is exactly why a naive approach that scans once fails, and why the choice of data structure matters so much.

The other common interpretation simply collapses runs to a single character ("aabbcc" → "abc"). It is simpler, and I will note where it differs, but the cascading-pair version is the one that trips people up in interviews, so it gets most of our attention.

Why the Naive Approach Fails

A beginner's instinct is to loop over the string and build a new one, skipping characters that match the previous one:

def remove_adjacent_naive(s: str) -> str:
    result = []
    for ch in s:
        if result and result[-1] == ch:
            result.pop()          # found a pair, remove it
        else:
            result.append(ch)
    return "".join(result)

This actually looks correct, and it is correct for the cascading problem, but if you wrote the naive version that only looks at the original neighbors (comparing s[i] to s[i+1] in a single pass), you would miss newly formed pairs. The lesson: any correct solution must remember everything that came before the current character, not just look ahead. That naturally points us toward a stack.

Not the most exciting part, but easily the most useful.

The Stack Approach

A stack is the ideal tool because it always exposes the most recently added element, which is exactly the character that could form a pair with the current one. The algorithm reads the string once, left to right:

  • Push a character onto the stack.
  • If it equals the character currently on top of the stack, you have an adjacent pair, so pop instead of keeping it.

After processing the entire string, whatever remains on the stack is the answer.

Step-by-step trace for "abbaca"

Step Char Stack (bottom → top) Action
1 a a push
2 b a b push
3 b a matches top b, pop
4 a (empty) matches top a, pop
5 c c push
6 a c a push

Final stack: ca. Matches our earlier reasoning.

Python implementation

def remove_adjacent_duplicates(s: str) -> str:
    """Remove adjacent duplicate pairs until none remain."""
    stack = []
    for

**Completing the function**

```python
def remove_adjacent_duplicates(s: str) -> str:
    """Return a new string where every occurrence of two identical,
    consecutive characters is deleted.  After each deletion the newly
    formed adjacency is examined automatically by the stack."""
    stack = []
    for ch in s:
        if stack and stack[-1] == ch:
            stack.pop()          # a pair was found – discard both copies
        else:
            stack.append(ch)     # keep the current character
    return ''.join(stack)

How it works – step‑by‑step on "abbaca"

Step Character Stack before action Action taken Stack after
1 a [] push [a]
2 b [a] push (b ≠ a) [a, b]
3 b [a, b] top is b, equal → pop [a]
4 a [a] top is a, equal → pop []
5 c [] push [c]
6 a [c] push (a ≠ c) [c, a]

After processing all characters the stack contains c a, i.Because of that, e. Plus, "ca". Joining the elements yields the required result Still holds up..


Why a naïve single‑pass scan fails

A common mistake is to look at original neighbours only:

# Incorrect idea – compares s[i] with s[i+1] while iterating once
result = []
for i, ch in enumerate(s):
    if i > 0 and s[i] == s[i-1]:
        # skip the previous character instead of adding current
        pass
    else:
        result.append(ch)
return ''.join(result)

This logic would miss newly created pairs such as in "abbaca", because after removing the middle bb the surrounding as become adjacent, but they are never seen together during a forward traversal. The solution therefore needs memory of everything that appeared before the current position—exactly what a stack provides.


Complexity analysis

  • Time: O(n) – each character is pushed at most once and popped at most once.
  • Space: O(n) in the worst case (when no deletions occur, the stack holds all characters).

Edge cases

Input Expected output Reason
"" ""
Reason
""
"aaa"
"a"
"abba"
"aaaa"
"abcabc"
"aa"
"aabbaa"

These cases highlight why the stack is so effective: it never needs to know the input length in advance, it handles empty and single-character strings naturally, and it keeps working correctly even when a single deletion triggers a cascade of further removals, as in "aabbaa".


Conclusion

Removing adjacent duplicates sounds like a local operation, but the moment a deletion brings two previously distant characters together, the problem becomes global in nature. Which means a naïve scan that only inspects original neighbours cannot account for these emergent adjacencies. The stack-based solution sidesteps this entirely: by remembering every character that survives up to the current position, it can always compare against the true neighbour—regardless of how many deletions preceded it It's one of those things that adds up..

The result is a solution that is both simple and optimal. Each character is examined once, giving linear time complexity, and the stack holds only what remains, giving linear space in the worst case. Beyond its efficiency, the approach is a textbook example of a reusable technique: whenever an operation must repeatedly collapse newly formed adjacencies—be it parentheses matching, backspace simulation in a text editor, or cancelling factors in an expression—the stack is almost always the right tool Practical, not theoretical..

What's New

Out This Week

Others Explored

In the Same Vein

Thank you for reading about 1047. Remove All Adjacent Duplicates In String. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home