Longest Common Subsequence (LCS) in Java

Longest Common Subsequence (LCS) problem, including its problem statement, solution, and Java implementation using the best possible approachDynamic Programming (Tabulation - Bottom-Up) for optimal performance.


Problem Statement: Longest Common Subsequence (LCS)

Given two strings text1 and text2, return the length of their longest common subsequence.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

Example:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The LCS is "ace" with length 3.

Optimal Solution: Dynamic Programming (Bottom-Up Tabulation)

💡 Idea:

We use a 2D DP array dp[i][j] where each cell represents the length of the LCS of the first i characters of text1 and the first j characters of text2.

Transition Formula:

  • If text1[i-1] == text2[j-1]
    dp[i][j] = 1 + dp[i-1][j-1]

  • Else
    dp[i][j] = max(dp[i-1][j], dp[i][j-1])


Java Code (Bottom-Up Approach)

public class LongestCommonSubsequence {

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

        // Create a 2D dp array
        int[][] dp = new int[m + 1][n + 1];

        // Fill the dp array from bottom up
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                // If characters match, move diagonally and add 1
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = 1 + dp[i - 1][j - 1];
                } else {
                    // Else take max from left or top
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        // The answer is in dp[m][n]
        return dp[m][n];
    }

    public static void main(String[] args) {
        String text1 = "abcde";
        String text2 = "ace";
        int result = longestCommonSubsequence(text1, text2);
        System.out.println("Length of LCS: " + result);  // Output: 3
    }
}

Time and Space Complexity

Complexity Value
Time O(m * n)
Space O(m * n)

You can optimize space to O(min(m, n)) by using a 1D rolling array instead of a 2D array if needed.


Bonus: To Reconstruct the LCS String

If you want to reconstruct the LCS itself, not just its length, we can backtrack from dp[m][n] to dp[0][0] while tracing the matching characters.

📢 Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! 😊 please leave a comment below. I’d love to hear from you! 👇

Happy coding! 💻✨

0 comments:

Post a Comment