Remove All Adjacent Duplicates In String

7 min read

Removing all adjacent duplicates in a string means eliminating repeated characters that appear next to each other until no neighboring characters are the same. On the flip side, this is a common string-processing problem in programming, interviews, data cleaning, and algorithm design. To give you an idea, applying the rule to the string abbaca removes adjacent duplicates step by step: abbacaaacaca. The final result is ca, because no two adjacent characters are identical anymore. Understanding how to solve this problem efficiently helps developers write cleaner code, improve performance, and handle more complex string manipulation tasks Turns out it matters..

Introduction to Removing Adjacent Duplicates in a String

A string is made up of characters arranged in a specific order. Sometimes, the same character appears multiple times in a row. These repeated neighboring characters are called adjacent duplicates Simple, but easy to overlook. That's the whole idea..

  • In "hello", the two l characters are adjacent duplicates.
  • In "aaaaabbbcc", the characters aaaaa, bbb, and cc are duplicate groups.
  • In "abba", the two b characters are adjacent duplicates.

The task of removing adjacent duplicates can be interpreted in a few ways. In one version, you remove only one copy of each adjacent duplicate, leaving one character from each group. In another version, you repeatedly remove adjacent duplicate pairs or groups until no more removals are possible. The second version is especially interesting because removing one duplicate group can cause new duplicates to become adjacent.

People argue about this. Here's where I land on it.

As an example, consider the string:

azxxzy

If we remove adjacent duplicates repeatedly:

azxxzy → azzy → ay

The final answer is ay. This happens because removing xx causes the two z characters to become adjacent, so they must also be removed.

The most efficient and widely used solution for this problem is the stack-based approach.

What Are Adjacent Duplicates?

Adjacent duplicates are characters that appear next to each other and are equal. They do not need to be separated by other characters. For example:

"aabbcc"

Here, aa, bb, and cc are adjacent duplicate groups Simple, but easy to overlook..

Even so, these are not adjacent duplicates:

"abab"

The repeated characters a and b appear, but they are not next to each other Still holds up..

Adjacent duplicate removal is different from removing all repeated characters from a string. For example:

"abca"

If you remove all repeated characters, one a might be removed. But if you remove only adjacent duplicates, the result is unchanged because the a characters are not adjacent Less friction, more output..

Problem Statement

Given a string, remove all adjacent duplicate characters until no two neighboring characters are the same.

Example 1:

Input:  "abbaca"
Output: "ca"

Explanation:

abbaca → aaca → ca

Example 2:

Input:  "azxxzy"
Output: "ay"

Explanation:

azxxzy → azzy → ay

Example 3:

Input:  "aaaa"
Output: ""

If every character is part of an adjacent duplicate group, the final string can become empty It's one of those things that adds up..

Why Use a Stack?

A stack is a data structure that follows the Last In, First Out principle. This means the last item added to the stack is the first item removed.

When processing a string from left to right, a stack is useful because it lets us compare the current character with the most recent character that has not been removed. If they are the same, we remove the previous character from the stack. If they are different, we add the current character to the stack.

This works perfectly for adjacent duplicate removal because only the most recent surviving character matters.

Stack-Based Solution

The stack-based approach processes each character in the string one at a time Which is the point..

The logic is simple:

  1. Start with an empty stack.
  2. Iterate through each character in the string.
  3. If the stack is not empty and the current character is the same as the top of the stack, remove the top character.
  4. Otherwise, add the current character to the stack.
  5. After processing all characters, convert the stack back into a string.

Python Example

def remove_adjacent_duplicates(s):
    stack = []

    for char in s:
        if stack and stack[-1] == char:
            stack.pop()
        else:
            stack.append(char)

    return "".join(stack)

Example Walkthrough

Let’s process the string:

azxxzy

Step by step:

Start: stack = []
Character: a
Stack: ['a']

Character: z
Stack: ['a', 'z']

Character: x
Stack: ['a', 'z', 'x']

Character: x
Top of stack is x, so remove it.
Stack: ['a', 'z']

Character: z
Top of stack is z, so remove it.
Stack: ['a']

Character: y
Stack: ['a', 'y']

Final result:

ay

JavaScript Example

function removeAdjacentDuplicates(s) {
  const stack = [];

  for (const char of s) {
    if (stack.Plus, length - 1] === char) {
      stack. length > 0 && stack[stack.pop();
    } else {
      stack.

  return stack.join("");
}

Example:

console.log(removeAdjacentDuplicates("

```javascript
console.log(removeAdjacentDuplicates("azxxzy")); // Output: "ay"

Complexity Analysis

Understanding the efficiency of this algorithm is crucial for handling large inputs. In practice, the time complexity of the stack-based solution is O(N), where N is the length of the input string. This is because we iterate through the string exactly once, and each character is pushed onto or popped from the stack at most once.

The space complexity is also O(N) in the worst-case scenario. If the input string contains no adjacent duplicates whatsoever, every character will be pushed onto the stack, requiring space proportional to the size of the input.

Edge Cases to Consider

While the stack-based approach handles most scenarios gracefully, it is helpful to consider edge cases when implementing this in production code:

  • Empty String: An empty string should simply return an empty string. The algorithm naturally handles this since the loop never executes and the stack remains empty.
  • Single Character: A string with only one character has no adjacent duplicates, so it should be returned as-is.

Additional Edge Cases

All characters are identical
When the input consists of a single repeated character, each new character immediately meets the condition “stack not empty and top equals current,” causing the stack to be popped. The process continues until the stack is empty, yielding an empty string. Take this: "bbbbb""" Simple, but easy to overlook..

Perfect alternation
If the string alternates between two different characters, no two adjacent symbols ever match, so the stack grows to contain every character. "ababab""ababab" Nothing fancy..

Mixed patterns
Strings that contain several independent pairs can be reduced step by step. "aabccbdd" → after processing becomes "abd".

Variations of the Algorithm

  1. Two‑pointer in‑place technique
    For mutable sequences (e.g., a character array), a single index can serve as both read and write pointer. The algorithm advances the read pointer, and when a match is found the write pointer moves back, effectively “deleting” the pair. This achieves O(1) auxiliary space when the input can be modified.

  2. Recursive formulation
    A concise recursive version repeatedly removes the first adjacent duplicate pair it encounters and recurses on the shortened string. While elegant, this approach can hit recursion depth limits on long inputs and is generally less efficient than the iterative stack method Turns out it matters..

  3. Functional language equivalents
    In languages that support immutable data structures, the same logic can be expressed using fold or reduce operations that maintain an accumulator list, mirroring the stack behavior.

Practical Applications

  • File path normalization – Removing .. and . components from a Unix‑style path simplifies navigation and prevents unintended directory traversal.
  • Data validation – Cleaning user‑entered strings such as passwords or identifiers where consecutive duplicate characters are disallowed.
  • Bioinformatics – Processing DNA or protein sequences to eliminate repetitive motifs that may indicate sequencing errors.

Complexity Recap

The stack‑based solution remains optimal: O(N) time, O(N) worst‑case space. The in‑place two‑pointer variant reduces auxiliary space to O(1) while preserving linear time, making it suitable for memory‑constrained environments.

Conclusion

The stack‑driven approach provides a clear, easy‑to‑implement, and efficient means of eliminating adjacent duplicate characters from a string. By iterating once and maintaining a simple LIFO structure, the algorithm guarantees linear performance and handles all edge cases—empty inputs, single characters, uniform strings, and alternating patterns—without additional branching logic. Variants such as in‑place two‑pointer manipulation or recursive solutions offer alternative trade‑offs, but the core idea remains the same: compare each element with the most recent unmatched element and cancel pairs as they appear. This technique’s simplicity, combined with its proven efficiency, makes it a go‑to solution for any problem that requires the removal of consecutive repetitions.

This changes depending on context. Keep that in mind The details matter here..

New on the Blog

Current Reads

Similar Ground

Keep Exploring

Thank you for reading about 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