Interview Question
Country: United States
@zortlord: I think my code does the minimum number of steps to get the permuted string, although I can't prove it yet.
It seems to me, that in worst case we need O(n^2) number of steps to make the permuted one.
Can you do the following example better than 10 steps?
ABCDE
EDCBA
int search(string src, int s, char ch)
{
for(int i=s;i<src.length();i++)
{
if(src[i] == ch)
return i;
}
return -1;
}
void pathSrc2Dst(string src, string dst)
{
int lenS = src.length();
int lenD = dst.length();
if(lenS != lenD)
{
cout<<" Invalid Input "<<endl;
return;
}
int d = 0, s = 0;
cout<<" "<<src;
while(true)
{
int loc = search(src, s, dst[d]);
if(loc<0)
{
cout<<" Invalid Input "<<endl;
return;
}
for(int i=loc;i>s;i--)
swap(src[i], src[i-1]);
s++;
d++;
cout<<" ----> "<<src;
if(s == src.length() || src == dst)
break;
}
cout<<endl;
}
int main()
{
string src, dst;
cout<<" Enter source :- ";
cin>>src;
cout<<" Enter destination :- ";
cin>>dst;
pathSrc2Dst(src, dst);
return 0;
}
Here's a simple code in C++.
Iterate over the permuted string and find the first position in original string which is equal to the current character of permuted. Then go back and swap one by one.
O(n^2)
- MehrdadAP June 25, 2015