You have a string "RGBBGBGR". Eliminate the pairs (two same chars adjacent to each other) recursively.
RGBBGBGR --> RGGBGR-->RBGR
Answer: Here recursively mean not a recursive function but to do it in the manner shown in example. Still we can do it recursively like below:
But this is very costly:Fun_rcur(string)
Remove pairs in string
1) Extra space (stack space for recursive calls)
2) You need to go through entire string in each recursive call.
Lets see an iterative approach for the same. We should check if we have character pair then cancel it and then check for next character and previous element. Keep canceling the characters until you either reach start of the array, end of the array or not find a pair.
void remove_pair(char* input)
int len = strlen(input);
int i, j = 0;
for (i=1; i <= len; i++)
while ((input[i] == input[j]) && (j >= 0))
input[++j] = input[i];
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.