Remove All Adjacent Duplicates In String - Complete Solution Guide
Remove All Adjacent Duplicates In String is LeetCode problem 1047, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It can be proven that the answer is unique . Example 1: Input: s = "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is
Detailed Explanation
This problem asks us to systematically reduce a given string by repeatedly identifying and removing any pair of adjacent, identical lowercase English letters. The process is not a one-shot pass; removing one duplicate pair might cause two previously separated characters to become adjacent, potentially forming a new duplicate pair that then also needs to be removed. For example, given "abbaca", the first step would likely remove "bb" to yield "aaca". Following this, the now adjacent "aa" would be removed, resulting in the final string "ca".
Solution Approach
The provided solution elegantly tackles this problem using a stack. The core idea is to process the input string characters one by one, building up a new string (conceptually represented by the stack) where all adjacent duplicates have been eliminated. When we encounter a character from the input string, we compare it against the character currently at the 'end' of our partially built result string. The stack's top element conveniently represents this 'end' character.
Step-by-Step Algorithm
- Step 1: Initialize an empty stack (or string builder).
- Step 2: Iterate through the input string character by character.
- Step 3: If the stack is not empty and the current character is equal to the top of the stack (or last character in the string builder), pop the top element from the stack (or remove the last character from the string builder).
- Step 4: Otherwise, push the current character onto the stack (or append it to the string builder).
- Step 5: After iterating through all characters, convert the stack contents (or string builder content) back into a string and return it.
Key Insights
- **Leveraging the stack's LIFO for 'effective adjacency':** A stack's Last-In, First-Out (LIFO) property is perfectly suited here. The `stack[-1]` (or `peek()` operation) always provides the most recently added character that *has not yet been removed*. This character is precisely the one that is 'effectively adjacent' to the current character being processed from the input string, allowing for immediate duplicate detection and removal.
- **Greedy, sequential processing handles cascading removals:** The solution processes the input string strictly from left to right. When a duplicate is found (current character matches `stack[-1]`), both are effectively discarded by popping from the stack and not pushing the current character. This 'backs up' our effective string, automatically allowing previously non-adjacent characters to become new neighbors, thus correctly handling the cascading nature of duplicate removals (e.g., 'abccba' -> 'abba' -> 'aa' -> '').
- **Efficient result construction without intermediate string overhead:** Instead of repeatedly building new substrings or concatenating strings (which can be computationally expensive, potentially leading to `O(N^2)` complexity if not careful), the stack merely performs `append` and `pop` operations on individual characters. The final, de-duplicated string is only constructed once at the very end by joining the characters left in the stack, making the overall process efficient.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: String, Stack.
Companies
Asked at: Geico, Grammarly, Paytm, Whatnot, Zoho.