Remove All Adjacent Duplicates in String II

You are given a string `s` and an integer `k`. A k duplicate removal picks `k` equal letters that sit next to each other in `s` and deletes them, so the parts on the left and right join together. Keep making k duplicate removals until none is possible, then return the final string. The answer is guaranteed to be unique.

30:00

Remove All Adjacent Duplicates in String II
medium
Free written solution
Topics
Companies

You are given a string s and an integer k. A k duplicate removal picks k equal letters that sit next to each other in s and deletes them, so the parts on the left and right join together. Keep making k duplicate removals until none is possible, then return the final string. The answer is guaranteed to be unique.

Example 1:
Input: {"s":"abcd","k":2}
Output: abcd
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

  • 2≤k≤1042 \leq k \leq 10^4

  • s contains only lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"abcd","k":2}

s, k = 2; struck letters left in a run of k

a

0

b

1

c

2

d

3

Scan left to right keeping a stack of [letter, run length] groups. When a group's run reaches k = 2, the whole run is deleted at once.

stack of [letter, count] groups (bottom → top)

0 groups

empty

runs removed 0
chars read 0 / 4
letters alive 0
Variables
VariableValue
k2
stack[]
DepthFunction Call
Stack empty
0/6