Remove All Adjacent Duplicates in String II in C++

C++Server Side ProgrammingProgramming

Suppose a string s is given, a k duplicate removal consists of choosing k adjacent and equal letters from string s and removing them causing the left and the right side of the deleted substring to concatenate together. We will repeatedly make k duplicate removals on the given string s until we cannot change any remaining. We have to find the final string after all such duplicate removals have been made. So if the input is like s = “deeedbbcccbdaa”, and k = 3, then the output will be “aa”, at first delete the “eee” and “ccc” and we will get “ddbbbaa”, then delete “bbb”, the string will be “dddaa”, then delete “ddd”, and the output will be “aa”

To solve this, we will follow these steps −

  • ans := empty string
  • create one stack for char-int pair, n := size of the string
  • for i in range 0 to n
    • x := s[i]
    • if stack is not empty and integer of the stack top element = k, then delete top element from stack
    • if i = n, then break
    • if stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1
    • otherwise increase the integer part of the stack top element, and increase i by 1
  • while stack is not empty
    • temp := stack top element
    • while integer part of temp is not 0,
      • ans := ans + character part of temp
      • decrease integer part of temp by 1
    • delete the top element from stack
  • reverse the ans string and return.

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   string removeDuplicates(string s, int k) {
      string ans = "";
      stack < pair<char, int> > st;
      int n = s.size();
      for(int i = 0; i <= n;){
         char x = s[i];
         if(!st.empty() && == k)st.pop();
         if(i == n)break;
         if(st.empty() || != x){
            st.push({x, 1});
         } else {
         pair <char, int> temp =;
         while(temp.second--) ans += temp.first;
      reverse(ans.begin(), ans.end());
      return ans;
   Solution ob;
   cout <<(ob.removeDuplicates("deeedbbcccbdaa", 3));




Published on 30-Apr-2020 16:16:14