This is the interview question
Given two words that are anagram of each other. Swap one word (only adjacent swapping of letters allowed) to reach to the other word ?
for example
given = abcd
target = dbac
to reach dbac
[Given] abcd
[1]bacd
[2]badc
[3]bdac
[4]dbac
I thought of solving it using edit distance, but edit distance does n't take into account only adjacent swapping of letters
What should be the approach to solve this?
My code using edit distance
#define STRING_X "abcd"
#define STRING_Y "dbac"
// Returns Minimum among a, b, c
int Minimum(int a, int b, int c)
{
return min(min(a, b), c);
}
// Recursive implementation
int EditDistanceRecursion( char *X, char *Y, int m, int n )
{
// Base cases
if( m == 0 && n == 0 )
return 0;
if( m == 0 )
return n;
if( n == 0 )
return m;
// Recurse
int left = EditDistanceRecursion(X, Y, m-1, n) + 1;
int right = EditDistanceRecursion(X, Y, m, n-1) + 1;
int corner = EditDistanceRecursion(X, Y, m-1, n-1) + (X[m-1] != Y[n-1]);
return Minimum(left, right, corner);
}
int main()
{
char X[] = STRING_X; // vertical
char Y[] = STRING_Y; // horizontal
printf("Minimum edits required to convert %s into %s is %d by recursion\n",
X, Y, EditDistanceRecursion(X, Y, strlen(X), strlen(Y)));
return 0;
}