Skip to main content
Back to problems
Leetcode
Medium
Stacks
Strings
Google
Meta
Remove All Adjacent Duplicates in String II

Remove groups of kk adjacent equal characters repeatedly until no such group remains.

Acceptance 0%
Problem Statement

Given a string s and an integer k, repeatedly delete any block of exactly k consecutive equal characters from the string. Continue applying this rule until no removable block remains.

Your task is to return the final string after all possible removals have been performed.

Because deleting one block can create a new adjacent block across the deletion boundary, the removals must be applied repeatedly until the string becomes stable.

Input Format

  • A string s consisting of lowercase English letters.
  • An integer k representing the block size to remove.

Output Format

  • Return the string that remains after all adjacent groups of length k have been removed repeatedly.

Constraints

  • 1s1051 \le |s| \le 10^5
  • 1k1041 \le k \le 10^4
  • s contains only lowercase English letters
  • The answer is guaranteed to fit in memory
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "deeedbbcccbdaa", k = 3

Output

"aa"

Explanation

Remove eee, then bbb, then ccc. The string becomes aa after all cascading removals are applied.

Example 2

Input

s = "pbbcggttciiippooaais", k = 2

Output

"ps"

Explanation

Repeatedly remove adjacent pairs such as bb, gg, tt, iii (after intermediate merges), pp, oo, aa, and ii until only ps remains.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.