Recursion: Remove K adjacent duplicate in a string

Problem Statement:

You are given a string and a value k.
You need to remove k adjacent duplicate from the array.

Example:

Input: s = "deeedbbcccbdaa" k = 2

Output: "aa"

Solution Explanation:

Below is the recursive solution along with the comments in the code.
for(auto i=1,c=1;i<s.size();++i)
{
 //check if the current character is different, reset the count
 if(s[i]!=s[i-1])
     c=1;
 //if the current char is same, increment c,
 //when c reaches k, then we found k consecutive duplicates
 else if(++c==k)
  //when we found duplicate, then create a new string as:
  //s.substr(0, i-k+1) will have everything before the duplicate sequence.
  //s.substr(i+1) : will have everything after the duplicate sequence.
     return solution(s.substr(0,i-k+1)+s.substr(i+1),k);
}
Time Complexity: O(1)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;


string solution(string s, int k) 
{
    
	for(auto i=1,c=1;i<s.size();++i)
	{
	    if(s[i]!=s[i-1])
	        c=1;
	    else if(++c==k)
	        return solution(s.substr(0,i-k+1)+s.substr(i+1),k);
	}
	return s;

}

int main() 
{
    string s = "deeedbbcccbdaa";
    cout << solution(s, 3) << endl; 
    return 0;
}

Output

aa
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *