I have a question regarding this problem and my solution. Given three sequences a,b,c - I used the logic of finding the longest common sub-sequence value of each pair (a,b), (b,c) and (c,a). Then finding the minimum of the three. Which should give us the longest common sub-sequence value.
I was wondering why my solution would not be robust? The code I used is below (in JAVA).
DRIVER CODE:
int result1 = DynamicProgramming.longestCommonSequence(a, b);
int result2 = DynamicProgramming.longestCommonSequence(b, c);
int result3 = DynamicProgramming.longestCommonSequence(c, a);
int temp = Math.min(result1, result2);
System.out.println(Math.min(result3, temp));
PROGRAM LOGIC:
public static int longestCommonSequence(int[] a, int[] b) {
int[][] aS = new int[a.length + 1][b.length + 1];
int tempAS;
for (int i = 0; i < aS.length; i++)
for (int j = 0; j < aS[0].length; j++) {
if (i == 0) {
aS[i][j] = j;
} else if (j == 0) {
aS[i][j] = i;
} else {
int ins = aS[i][j - 1] + 1;
int del = aS[i - 1][j] + 1;
int mat = aS[i - 1][j - 1];
tempAS = Math.min(ins, del);
if (a[i - 1] == b[j - 1])
aS[i][j] = Math.min(mat, tempAS);
else
aS[i][j] = tempAS;
}
}
return (a.length + b.length - aS[a.length][b.length]) / 2;
}
The program works in all test cases I have tried. But when I submitted it to an online automatic tester it failed on the last test case(edx course). I am unable to think of a situation where the solution would fail. Any help would be greatly appreciated.
We can assume that all input values are valid integers and the arrays a,b,c are not null.
PS: I have already found and alternate solution that passes all the tests. But I was curious to know the flaw in my logic. Thanks.