Remove All Adjacent Duplicates in String II

Medium

Description

Given a string s and an integer k, repeatedly remove k adjacent equal characters until no more can be removed. Return the final string after all removals.

Examples

Input:s = "deeedbbcccbdaa", k = 3
Output:"aa"
Explanation:

Remove eee, ccc, ddd.

Input:s = "abbbaaca", k = 4
Output:abaca
Explanation:

First, looking for 4 consecutive identical characters. There are only 3 'b's together ("bbb"), so no removal occurs in the first pass. Since no group of 4 adjacent duplicates exists, the string remains unchanged.

Input:s = "aaabbaaaa", k = 3
Output:a
Explanation:

Repeatedly removing groups of 3 adjacent identical characters: "aaabbaaaa" → remove "aaa" → "bbaaaa" → remove "aaa" from the four a's → "bba". The final result after all possible removals is "a".

Constraints

  • 1 ≤ s.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!