Problem · String

Remove Adjacent Duplicates in String II

Learn this problem
MediumAttentive logoAttentiveFULLTIMEONSITE INTERVIEW

Problem statement

Given a lowercase string s and an integer k, repeatedly remove any group of exactly k adjacent equal characters. Concatenate the remaining parts after each removal.

Return the unique final string after no removable group remains.

Function

removeDuplicates(s: String, k: int) → String

Examples

Example 1

s = "deeedbbcccbdaa"k = 3return = "aa"

Removing eee and ccc makes the three b characters adjacent. Removing them leaves aa.

Example 2

s = "pbbcggttciiippooaais"k = 2return = "ps"

Each adjacent pair is removed as it forms, including pairs created by earlier removals.

Example 3

s = "abcd"k = 2return = "abcd"

No two adjacent characters are equal.

Constraints

  • 1 <= s.length <= 100000.
  • s contains only lowercase English letters.
  • 2 <= k <= s.length.
drafts saved locally
public String removeDuplicates(String s, int k) {
  // Write your code here.
}
s"deeedbbcccbdaa"
k3
expected"aa"
checking account