1

I have the following code in Java:

public static int Secret(String a, String b, int x, int y){
    if ((x == -1) || (y == -1)) {
        return 0;
    }

    if (a.charAt(x) == b.charAt(y)) {
        return Secret(a, b, x-1, y-1) + 1;
    } else {
        int left = Secret(a, b, x, y-1);
        int up = Secret(a, b, x-1, y);

        if (left > up) {
            return left ;
        } else {
            return up;
        }
    }

    return -1; 
}

This code looks like the Longest Common Substring Problem but with a garbage complexity. I am supposed to opmitize it to O(mn) (space and time).

I tried following the algorithm on the wikipedia (https://en.wikipedia.org/wiki/Longest_common_substring_problem), that is O(mn) (space and time).

public static int iterativeLCS(String a, String b, int x, int y) {
        int[][] L = new int[x+1][y+1];
        int z = 0;

        for (int i = 0; i <= x; i++) {
            for (int j = 0; j <= y; j++) {
                if (a.charAt(i) == b.charAt(j)) {
                    if ((i == 0) || (j == 0)) {
                        L[i][j] = 1;
                    } else {
                        L[i][j] = L[i-1][j-1] + 1;
                    }

                    if (L[i][j] > z) {
                        z = L[i][j];
                    }
                } else {
                    L[i][j] = 0;
                }
            }
        }
    }

But the results don't match for some inputs. For example:

xalmandriatico
talcolaritriom
13
13

Expected output (using the recursive alg): 8
Actual output (using the iterative alg from wikipedia): 2

Any idea on what I have to do?

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
Higor
  • 11
  • 2
  • Add memoization to your current recursive solution and it will be O(mn) – juvian Nov 28 '18 at 20:40
  • The previous comment says it all, but more details: Use an array just like the wiki and before you start computing, check if there's a stored result already. Use a marker value like -1 for "not yet computed". `+++` The very first sentence in wiki explain the different results. – maaartinus Nov 29 '18 at 02:59

0 Answers0