Remove All Adjacent Duplicates in String II - Problem

You are given a string s and an integer k. A k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

Input & Output

Example 1 — Basic Case
$ Input: s = "abccba", k = 2
Output: ""
💡 Note: Remove "cc" → "abba", then remove "bb" → "aa", then remove "aa" → "" (empty string).
Example 2 — Multiple Removals
$ Input: s = "abbbaaca", k = 3
Output: "ca"
💡 Note: First remove "bbb" → "abaaca", then remove "aaa" → "ca". No more k=3 adjacent duplicates.
Example 3 — No Removals
$ Input: s = "aa", k = 3
Output: "aa"
💡 Note: No groups of 3 consecutive identical characters exist, so string remains unchanged.

Constraints

  • 1 ≤ s.length ≤ 105
  • 2 ≤ k ≤ 104
  • s only contains lower case English letters.

Visualization

Tap to expand
Remove All Adjacent Duplicates in String II INPUT String s = "abccba" a b c c b a 0 1 2 3 4 5 k = 2 Stack Structure: [char, cnt] ['a', 1] ['b', 1] Track char + consecutive count ALGORITHM STEPS 1 Initialize Stack Stack stores [char, count] 2 Process Each Char If top matches, increment 3 Check Count = k Pop if count reaches k 4 Build Result Reconstruct from stack Trace for "abccba", k=2: 'a' --> [('a',1)] 'b' --> [('a',1),('b',1)] 'c' --> [('a',1),('b',1),('c',1)] 'c' --> cnt=2=k, POP! 'b' --> [('a',1),('b',2)] POP! 'a' --> [('a',2)] POP! FINAL RESULT After all removals: "" (Empty String) Removal Sequence: ab[cc]ba --> abba a[bb]a --> aa [aa] --> "" Output: "" OK - All duplicates removed Key Insight: Use a stack to track consecutive characters with their counts. When count reaches k, pop from stack. This handles cascading removals automatically. Time: O(n), Space: O(n). TutorialsPoint - Remove All Adjacent Duplicates in String II | Optimal Solution (Stack)
Asked in
Facebook 45 Amazon 35 Google 30 Microsoft 25
67.5K Views
Medium Frequency
~15 min Avg. Time
1.9K 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