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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code