LeetCode 1940: Longest Common Subsequence Between Sorted Arrays Solution
Master LeetCode problem 1940 (Longest Common Subsequence Between Sorted Arrays), 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.
1940. Longest Common Subsequence Between Sorted Arrays
Problem Explanation
Explanation:
The problem asks us to find the longest common subsequence between two sorted arrays. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.To solve this problem efficiently, we can use a dynamic programming approach. We will create a 2D array to store the length of the longest common subsequence up to each pair of elements from both arrays.#### Algorithmic Steps:
- Initialize a 2D array
dpof sizen x m, wherenis the length of the first array andmis the length of the second array. - Iterate over each pair of elements from both arrays.
- If the elements are equal, update
dp[i][j]todp[i-1][j-1] + 1(length of common subsequence up to the previous pair plus 1). - If the elements are not equal, update
dp[i][j]to the maximum ofdp[i-1][j]anddp[i][j-1]. - The final answer will be
dp[n-1][m-1], which represents the length of the longest common subsequence.
:
Solution Code
class Solution {
public int longestCommonSubsequence(int[] nums1, int[] nums2) {
int n = nums1.length;
int m = nums2.length;
int[][] dp = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (nums1[i] == nums2[j]) {
dp[i][j] = (i > 0 && j > 0) ? dp[i-1][j-1] + 1 : 1;
} else {
int prev1 = (i > 0) ? dp[i-1][j] : 0;
int prev2 = (j > 0) ? dp[i][j-1] : 0;
dp[i][j] = Math.max(prev1, prev2);
}
}
}
return dp[n-1][m-1];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1940 (Longest Common Subsequence Between Sorted Arrays)?
This page provides optimized solutions for LeetCode problem 1940 (Longest Common Subsequence Between Sorted Arrays) 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 1940 (Longest Common Subsequence Between Sorted Arrays)?
The time complexity for LeetCode 1940 (Longest Common Subsequence Between Sorted Arrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1940 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1940 in Java, C++, or Python.