Introduction: What Is LeetCode 1047 Remove All Adjacent Duplicates In String?
If you are grinding LeetCode for coding interviews at companies like Google, Amazon, or Microsoft, LeetCode 1047 Remove All Adjacent Duplicates In String is a problem you cannot skip. It is one of the most elegant examples of the stack simulation pattern and appears frequently as a warmup or follow-up question in technical rounds.
In this article we will cover everything you need — plain English explanation, real life analogy, 3 Java approaches with dry runs, complexity analysis, common mistakes, FAQs, and similar problems to practice next.
Here is the problem link-: Leetcode 1047
What Is the Problem Really Asking?
You are given a string. Keep scanning it and whenever you find two same letters sitting next to each other, remove both of them. After removing, the letters around them might now become adjacent and form a new pair — so you keep doing this until no more adjacent duplicates exist.
Example walkthrough for "abbaca":
"abbaca"→bbare adjacent duplicates → remove →"aaca""aaca"→aaare adjacent duplicates → remove →"ca""ca"→ no adjacent duplicates → done!- ✅ Output:
"ca"
Real Life Analogy — Think of Popping Bubbles
Imagine a row of colored bubbles. Whenever two bubbles of the same color are next to each other, they pop and disappear. After they pop, the bubbles on either side might now touch each other — and if they are the same color, they pop too! You keep going until no two same-colored bubbles are touching.
That chain reaction is exactly what this problem simulates. And the best tool to handle that chain reaction? A stack.
Approach 1: Brute Force (Beginner Friendly)
The Idea
Scan the string repeatedly. Every time you find two adjacent equal characters, remove them. Keep doing this until a full pass finds nothing to remove.
This is easy to understand but very slow. For each pair found, you restart the entire scan. With n up to 100,000, this will get Time Limit Exceeded on LeetCode. Use it only to build intuition.
Time Complexity: O(n²) — repeated passes over the string Space Complexity: O(n) — StringBuilder storage
Approach 2: Stack Based Solution (Classic Interview Approach)
The Idea
A stack is perfect here because of one key observation — when you remove a pair, the character that was before the pair is now adjacent to the character after the pair. That is a Last In First Out situation, which is exactly what a stack handles naturally.
Algorithm:
- If the current character matches the top of the stack → pop (they cancel each other)
- Otherwise → push the current character onto the stack
- At the end, the stack contains your final answer
Dry Run — "abbaca"
We go character by character and check against the top of the stack:
a→ stack empty, push → stack:[a]b→ top isa, not equal, push → stack:[a, b]b→ top isb, equal! pop → stack:[a]a→ top isa, equal! pop → stack:[]c→ stack empty, push → stack:[c]a→ top isc, not equal, push → stack:[c, a]
Stack remaining: [c, a] → reverse → ✅ "ca"
Notice how after removing bb, the two as automatically become adjacent and get caught — the stack handles this chain reaction naturally without any extra logic!
Time Complexity: O(n) — single pass through the string Space Complexity: O(n) — stack holds up to n characters
Approach 3: StringBuilder as Stack (Optimal Solution) ✅
The Idea
This is your own solution and the best one! Instead of using a separate Stack<Character>, we use StringBuilder itself as a stack:
sb.append(c)acts as pushsb.deleteCharAt(sb.length() - 1)acts as popsb.charAt(sb.length() - 1)acts as peek
No extra data structure, no boxing of char into Character objects, and no reversal needed at the end. Clean, fast, and minimal.
Dry Run — "azxxzy"
a→ sb empty, append →"a"z→ last char isa, not equal, append →"az"x→ last char isz, not equal, append →"azx"x→ last char isx, equal! delete →"az"z→ last char isz, equal! delete →"a"y→ last char isa, not equal, append →"ay"
✅ Final Answer: "ay"
Again, notice the chain reaction — after xx was removed, z and z became adjacent and got removed too. The StringBuilder handles this perfectly in a single pass!
Time Complexity: O(n) — one pass, every character processed exactly once Space Complexity: O(n) — StringBuilder storage
Why StringBuilder Beats Stack in Java
When you use Stack<Character> in Java, every char primitive gets auto-boxed into a Character object. That means extra memory allocation for every single character. With StringBuilder, you work directly on the underlying char array — faster and leaner. Plus you skip the reversal step entirely.
For an interview, the Stack approach is great for explaining your thought process clearly. But for the final submitted solution, StringBuilder is the way to go.
Common Mistakes to Avoid
Not checking sb.length() != 0 before peeking If the StringBuilder is empty and you call sb.charAt(sb.length() - 1), you will get a StringIndexOutOfBoundsException. Always guard this check — even if the problem guarantees valid input, it shows clean coding habits.
Thinking you need multiple passes Many beginners think you need to scan the string multiple times because of chain reactions. The stack handles chain reactions automatically in a single pass. Trust the process!
Forgetting to reverse when using Stack Since a stack gives you characters in reverse order when you pop them, you must call .reverse() at the end. With StringBuilder you do not need this.
How This Fits Into the Stack Simulation Pattern
By now you might be noticing a theme across multiple problems:
LeetCode 3174 Clear Digits — digit acts as backspace, deletes closest left non-digit
LeetCode 2390 Removing Stars — star acts as backspace, deletes closest left non-star
LeetCode 1047 Remove Adjacent Duplicates — character cancels itself if it matches the top of stack
All three use the exact same StringBuilder-as-stack pattern. The only difference is the condition that triggers a deletion. This is why pattern recognition is the real skill — once you internalize this pattern, you can solve a whole family of problems in minutes.
FAQs — People Also Ask
Q1. What is the best approach for LeetCode 1047 in Java? The StringBuilder approach is the best. It runs in O(n) time, uses O(n) space, requires no extra data structure, and avoids the reversal step needed with a Stack.
Q2. Why does a stack work for removing adjacent duplicates? Because whenever you remove a pair, the characters around them become the new neighbors. A stack naturally keeps track of the most recently seen character, so it catches these chain reactions without any extra logic.
Q3. What is the time complexity of LeetCode 1047? The optimal solution runs in O(n) time and O(n) space, where n is the length of the input string.
Q4. Is LeetCode 1047 asked in coding interviews? Yes, it is commonly asked as a warmup problem or follow-up at companies like Google, Amazon, and Adobe. It tests your understanding of stack-based string manipulation.
Q5. What is the difference between LeetCode 1047 and LeetCode 1209? LeetCode 1047 removes pairs of adjacent duplicates. LeetCode 1209 is the harder version — it removes groups of k adjacent duplicates, requiring you to store counts alongside characters in the stack.
Similar LeetCode Problems to Practice Next
- 2390. Removing Stars From a String — Medium — star as backspace
- 3174. Clear Digits — Easy — digit as backspace
- 844. Backspace String Compare — Easy — compare two strings after backspaces
- 1209. Remove All Adjacent Duplicates in String II — Medium — harder version with k duplicates
- 735. Asteroid Collision — Medium — stack simulation with collision logic
Conclusion
LeetCode 1047 Remove All Adjacent Duplicates In String is a beautiful problem that teaches you one of the most powerful and reusable patterns in DSA — stack simulation. The moment you spot that a removal can cause a chain reaction of more removals, you know a stack is your best friend.
The StringBuilder solution is clean, optimal, and interview-ready. Master it, understand why it works, and you will be able to tackle the entire family of stack simulation problems with confidence.
Found this helpful? Share it with friends preparing for coding interviews




