0

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.

1 Answers1

3

if string a was aaaaaaaabbbbbbb

and string b was bbbbbbbbccccccc

and string c was ccccccccaaaaaaa

then (a,b) have a common subsequence of length 7 and (b,c) have a common subsequence of length 7 and (c,a) have a common subsequence of length 7

but is there a subsequence that is common to all 3? (Answer: no... and so the idea of just taking the min of the 3 pairwise comparisons is flawed)

JimN
  • 340
  • 2
  • 10
  • Thank you. I was having trouble visualizing this test case. – Sudarshan Vs Sep 04 '20 at 08:10
  • Since this wasn't a java issue, you could re-phrase the question just in terms of multiple LCS without the java code and this answer would still stand. – JimN Sep 04 '20 at 08:13