Remove All Adjacent Duplicates in String II

medium stack string

Problem

Given a string s and an integer k, repeatedly remove any k adjacent identical characters until no more can be removed. Return the final string.

Inputs = "deeedbbcccbdaa", k = 3
Output"aa"
"deeedbbcccbdaa" → "ddbbcccbdaa" → "ddbbbdaa" → "dddaa" → "aa".

def remove_duplicates(s, k):
    stack = []  # list of [char, count]
    for c in s:
        if stack and stack[-1][0] == c:
            stack[-1][1] += 1
            if stack[-1][1] == k:
                stack.pop()
        else:
            stack.append([c, 1])
    return "".join(ch * cnt for ch, cnt in stack)
function removeDuplicates(s, k) {
  const stack = []; // [char, count]
  for (const c of s) {
    if (stack.length && stack[stack.length - 1][0] === c) {
      stack[stack.length - 1][1]++;
      if (stack[stack.length - 1][1] === k) stack.pop();
    } else {
      stack.push([c, 1]);
    }
  }
  return stack.map(([ch, cnt]) => ch.repeat(cnt)).join("");
}
class Solution {
    public String removeDuplicates(String s, int k) {
        Deque<int[]> stack = new ArrayDeque<>(); // [char, count]
        for (char c : s.toCharArray()) {
            if (!stack.isEmpty() && stack.peek()[0] == c) {
                stack.peek()[1]++;
                if (stack.peek()[1] == k) stack.pop();
            } else {
                stack.push(new int[]{c, 1});
            }
        }
        StringBuilder sb = new StringBuilder();
        Iterator<int[]> it = stack.descendingIterator();
        while (it.hasNext()) {
            int[] e = it.next();
            for (int i = 0; i < e[1]; i++) sb.append((char) e[0]);
        }
        return sb.toString();
    }
}
string removeDuplicates(string s, int k) {
    vector<pair<char,int>> st;
    for (char c : s) {
        if (!st.empty() && st.back().first == c) {
            st.back().second++;
            if (st.back().second == k) st.pop_back();
        } else {
            st.push_back({c, 1});
        }
    }
    string out;
    for (auto& p : st) out.append(p.second, p.first);
    return out;
}
Time: O(n) Space: O(n)