Remove All Adjacent Duplicates in String II Problem
Description
LeetCode Problem 1209.
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.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^52 <= k <= 10^4sonly contains lowercase English letters.
Solution
Approach: Stack of Runs
Simulating the removals by scanning the string again and again can take O(n2/k) time. Notice that a removal only matters to the letters right around it: after k equal letters disappear, their left and right neighbors meet and may form a new run. A stack handles this in one pass.
Keep a stack of runs: a letter and how many times it repeats in a row, for the part of the string that survives so far. For each letter c of s:
- If the top run is the same letter, add one to its count. If the count reaches
k, pop the run: thosekletters are removed. - Otherwise push a new run
(c, 1).
After a pop, the new top run is the one before the removed letters, so the next letter is compared with it. This is exactly the "left and right sides join" step. For example, with "deeedbbcccbdaa" and k = 3, removing "eee" leaves the top run d, which the next d extends to dd. Later, once "ccc" and then "bbb" are gone, dd is on top again and the third d completes it.
At the end, write out each remaining run.
Complexity: O(n) time and O(n) space for the stack.
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = [] # [char, run length] for the runs that are left so far
for c in s:
if stack and stack[-1][0] == c:
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop() # k equal letters in a row: remove them
else:
stack.append([c, 1])
return "".join(c * count for c, count in stack)