LeetCode 1143: Longest Common Subsequence Solution

Master LeetCode problem 1143 (Longest Common Subsequence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1143. Longest Common Subsequence

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will create a 2D array to store the length of the longest common subsequence up to each point in the two strings. We will iterate over the strings and fill in the array based on certain conditions. At the end, the value in the bottom right corner of the array will represent the length of the longest common subsequence.

Here are the steps:

  1. Create a 2D array dp of size (text1.length()+1) x (text2.length()+1).
  2. Initialize the first row and first column of the array with zeros.
  3. Iterate over the strings text1 and text2.
  4. If the characters at the current indices are the same, update dp[i][j] = dp[i-1][j-1] + 1.
  5. Otherwise, update dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
  6. The value at dp[text1.length()][text2.length()] will be the length of the longest common subsequence.

The time complexity of this approach is O(mn), where m and n are the lengths of the input strings. The space complexity is also O(mn) since we are using a 2D array to store intermediate results.

Solution Code

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m+1][n+1];
        
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (text1.charAt(i-1) == text2.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        
        return dp[m][n];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1143 (Longest Common Subsequence)?

This page provides optimized solutions for LeetCode problem 1143 (Longest Common Subsequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1143 (Longest Common Subsequence)?

The time complexity for LeetCode 1143 (Longest Common Subsequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1143 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1143 in Java, C++, or Python.

Back to LeetCode Solutions