Leetcode – Remove All Adjacent Duplicates In String Solution

Spread the love

One of the intriguing aspects of algorithmic challenges is how they often mirror real-world tasks. Removing adjacent duplicates from strings is not just an academic challenge; it finds relevance in text processing, data cleaning, and other tasks in the software realm. The “Remove All Adjacent Duplicates In String” problem on Leetcode provides an engaging platform to apply and hone one’s problem-solving skills. This article aims to dissect the problem, lay down the fundamental concepts, suggest multiple approaches, and elucidate Python solutions.

Table of Contents:

  1. Problem Statement
  2. Intuition Behind the Problem
  3. Different Solution Approaches
  4. Python Implementations
  5. Testing and Time Complexity
  6. Final Thoughts

1. Problem Statement:

Given a string s, remove all the adjacent duplicates and return the final string. Two letters are adjacent duplicates if they are equal and next to each other.

Example:

Input: "abbaca"
Output: "ca"

2. Intuition Behind the Problem:

Imagine you’re working with a stack of cards. Whenever you see two cards of the same kind appearing consecutively, you remove them. The process of solving this problem mirrors this concept.

3. Different Solution Approaches:

  1. Brute Force: Repeatedly scan the string to remove any pair of adjacent duplicates until no more such pairs exist.
  2. Stack-Based: Use a stack to efficiently track the characters and pop the top when a duplicate is found.

4. Python Implementations:

1. Brute Force Approach:

def removeDuplicates_brute(s: str) -> str:
    found = True
    while found:
        found = False
        i = 0
        while i < len(s) - 1:
            if s[i] == s[i+1]:
                s = s[:i] + s[i+2:]
                found = True
                break
            i += 1
    return s

2. Stack-Based Approach:

The stack-based approach offers a more efficient solution. We can iterate over the string, and for each character:

  • If the stack is empty, push the character onto the stack.
  • If the stack’s top has the same character, pop the stack.
  • Otherwise, push the character onto the stack.

By the end of this process, the stack will have the resultant string without any adjacent duplicates.

def removeDuplicates_stack(s: str) -> str:
    stack = []
    for char in s:
        if stack and stack[-1] == char:
            stack.pop()
        else:
            stack.append(char)
    return ''.join(stack)

5. Testing and Time Complexity:

Let’s validate our solutions against some test cases:

print(removeDuplicates_brute("abbaca"))  # Expected output: "ca"
print(removeDuplicates_stack("abbaca"))  # Expected output: "ca"

print(removeDuplicates_brute("abbbaca"))  # Expected output: "aca"
print(removeDuplicates_stack("abbbaca"))  # Expected output: "aca"

In terms of time complexity:

  • The brute force approach can, in the worst case, take O(n^2) for a string of length n.
  • The stack-based approach is more efficient with a time complexity of O(n).

6. Final Thoughts:

The “Remove All Adjacent Duplicates In String” problem highlights the elegance of the stack data structure in solving specific challenges. While the brute force approach offers a straightforward method, it’s often worthwhile to explore more efficient alternatives, especially when dealing with large data.

Leave a Reply