Java: Longest Common Subsequence

Thought Process

The problem requires finding the length of the longest common subsequence between two strings. We use a dynamic programming to solve this. We create a 2D array 't' where t[i][j] represents the length of the longest common subsequence between the first 'i' characters of 'text1' and the first 'j' characters of 'text2'. If the characters at the current positions match, we increment the value from the diagonal cell. Otherwise, we take the maximum value from the left or top cell.

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        
        int m = text1.length();
        int n = text2.length();

        int[][] t = new int[m+1][n+1];

        for(int i=0;i<=m;i++){
            for(int j=0;j<=n;j++){

                if(i==0 || j==0)
                    t[i][j] = 0;

                else{

                    if(text1.charAt(i-1)==text2.charAt(j-1))
                        t[i][j] = 1 + t[i-1][j-1];
                    else
                        t[i][j] = Math.max(t[i-1][j],t[i][j-1]);
                }   
            }
        }
        return t[m][n];
    }
}

Code Complexity

Time Complexity: O(n * m)

The algorithm iterates through each character of both strings, resulting in a time complexity of O(n * m), where n and m are the lengths of the strings.

Space Complexity: O(n * m)

The algorithm uses a 2D array of size (n+1) x (m+1) to store intermediate results.

Code copied!