Remove All Adjacent Duplicates In String - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abbaca"
Output: "ca"
💡 Note: First remove "bb" to get "aaca", then remove "aa" to get "ca". No more adjacent duplicates exist.
Example 2 — Complete Removal
$ Input: s = "azxxzy"
Output: "ay"
💡 Note: Remove "xx" to get "azzy", then remove "zz" to get "ay". Final result is "ay".
Example 3 — No Duplicates
$ Input: s = "abc"
Output: "abc"
💡 Note: No adjacent duplicates exist, so the string remains unchanged.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters

Visualization

Tap to expand
Remove All Adjacent Duplicates In String INPUT String s = "abbaca" a 0 b 1 b 2 a 3 c 4 a 5 Adjacent Duplicates Stack-based Approach Stack (LIFO) Push/Pop chars Compare top with current ALGORITHM STEPS 1 Initialize Stack Create empty stack to store characters 2 Iterate String Process each char from left to right 3 Compare and Act If top == current: Pop Else: Push current 4 Build Result Stack contains final string (bottom to top) Trace: "abbaca" a --> stack: [a] b --> stack: [a,b] b --> pop! stack: [a] a --> pop! stack: [] c --> stack: [c] a --> stack: [c,a] FINAL RESULT Output: "ca" c a OK - Complete! Removal Steps: "abbaca" Remove "bb": "aaca" Remove "aa": "ca" No more duplicates! Key Insight: Using a stack allows O(n) time complexity. When we encounter a character matching the stack's top, we pop (remove the duplicate pair). Otherwise, we push the character. This handles cascading removals automatically since previous characters are preserved in the stack for future comparisons. TutorialsPoint - Remove All Adjacent Duplicates In String | Stack-based Optimal Solution
Asked in
Amazon 45 Microsoft 30 Google 25
180.0K Views
Medium Frequency
~15 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen