Longest Common Subsequence in Python and Java
In this tutorial, we will learn LeetCode #1143: Longest Common Subsequence in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Longest Common Subsequence Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use two dimensional dynamic programming because it gives a clean and optimized solution.
Example input: text1 = "abcde", text2 = "ace" Expected result: Output: 3 Explanation: The common subsequence is ace.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: text1 = "abcde", text2 = "ace" Approach: two dimensional dynamic programming We update variables step by step until we reach: Output: 3
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why two dimensional dynamic programming is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. text1 = "abcde", text2 = "ace" We will solve it using two dimensional dynamic programming. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: 3 Why? The common subsequence is ace.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: 3
Example 1
Input: text1 = "abcde", text2 = "ace" Output: Output: 3 Explanation: The common subsequence is ace.
Example 2
Input: text1 = "stone", text2 = "longest" Output: 3 Explanation: One common subsequence is 'one'.
Python Code
Here is the complete Python solution for LeetCode #1143.
class CommonSubsequenceFinder:
def longest_common_subsequence(self, text1, text2):
rows = len(text1)
cols = len(text2)
dp = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(1, rows + 1):
for c in range(1, cols + 1):
if text1[r - 1] == text2[c - 1]:
dp[r][c] = 1 + dp[r - 1][c - 1]
else:
dp[r][c] = max(dp[r - 1][c], dp[r][c - 1])
return dp[rows][cols]
finder = CommonSubsequenceFinder()
print(finder.longest_common_subsequence("abcde", "ace")) # Output: 3
print(finder.longest_common_subsequence("pmjghexybyrgzczy", "hafcdqbgncrcbihkd"))Java Code
Here is the complete Java solution for LeetCode #1143.
class CommonSubsequenceFinder {
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
for (int r = 1; r <= text1.length(); r++) {
for (int c = 1; c <= text2.length(); c++) {
if (text1.charAt(r - 1) == text2.charAt(c - 1)) {
dp[r][c] = 1 + dp[r - 1][c - 1];
} else {
dp[r][c] = Math.max(dp[r - 1][c], dp[r][c - 1]);
}
}
}
return dp[text1.length()][text2.length()];
}
public static void main(String[] args) {
CommonSubsequenceFinder finder = new CommonSubsequenceFinder();
System.out.println(finder.longestCommonSubsequence("abcde", "ace")); // Output: 3
System.out.println(finder.longestCommonSubsequence("abcd", "bd")); // Output: 2
}
}Time and Space Complexity
Time Complexity: O(m * n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(m * n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #1143: Longest Common Subsequence becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.