Question:
You have a string "RGBBGBGR". Eliminate the pairs (two same chars adjacent to each other) recursively.
Example:
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)
{
if pairs
Remove pairs in string
Fun_recur(string)
Else
Return
}
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.
Code:
void remove_pair(char* input)
{
int len = strlen(input);
int i, j = 0;
for (i=1; i <= len; i++)
{
//Cancel pairs
while ((input[i] == input[j]) && (j >= 0))
{
i++;
j--;
}
input[++j] = input[i];
}
return;
}
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.
Good one !!
Thanks Shre!
The condition should be changed to
while ((j >= 0) && (input[i] == input[j]))
otherwise it might segfault in cases j < 0.
interviewer wants from me recursive solution can u provide that dont worry about stack memory
@Bhuwan: negative indexes does not cause seg fault. Though you can change the condition as u wrote.
@Anonymous: I have given recursive algorithm in this post. Code can be easily produced with that.
I think we can use a stack to do it in O(n).
Code:
-----
#include
#include
using namespace std;
void print(list S)
{
list::reverse_iterator it;
for(it = S.rbegin(); it != S.rend(); it++)
cout << *it;
cout << endl;
}
void getString(char c[], int n)
{
list S;
if(n == 0)
return;
S.push_front(c[0]);
int i = 1;
while(!S.empty())
{
while(!S.empty() && (S.front() == c[i]))
{
S.pop_front();
i++;
if(i == n) break;
}
//print(S);
if(i == n) break;
S.push_front(c[i]);
i++;
}
print(S);
}
int main(void)
{
char s[] = "RGBBGBGR";
int n = 8;
getString(s, n);
return 0;
}
char *rem_rec(char *str, int cur_pos)
{
if(*(str + cur_pos) == '\0')
return;
int i;
static int count = 0;
if(*(str + cur_pos) == *(str + cur_pos + 1))
{
count++;
i = cur_pos;
while(i!= 0) {
swap(str + i + 1, str + i - 1);
i--;
}
}
rem_rec(str, cur_pos + 1);
return (str+(2*count));
}
You did an excellent job! This is a very useful article. This appeals to me much. It is quite beneficial to my research. It clearly demonstrates your enthusiasm for the subject. I'm hoping you'll provide more details regarding the software. Please continue to share. Custom Website Development