#1035
Uncrossed Lines
MediumArrayDynamic ProgrammingDynamic ProgrammingLongest Common Subsequence
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
The optimal solution uses dynamic programming to build a table that keeps track of the maximum number of uncrossed lines that can be formed up to each index of nums1 and nums2. This approach is efficient and avoids redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D DP array where dp[i][j] represents the maximum number of uncrossed lines that can be formed using nums1[0..i-1] and nums2[0..j-1].
- 2Step 2: Iterate through each element of nums1 and nums2. If nums1[i-1] equals nums2[j-1], set dp[i][j] = dp[i-1][j-1] + 1. Otherwise, set dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
- 3Step 3: The answer will be in dp[nums1.length][nums2.length].
solution.py15 lines
1# Full working Python code
2
3def maxUncrossedLines(nums1, nums2):
4 m, n = len(nums1), len(nums2)
5 dp = [[0] * (n + 1) for _ in range(m + 1)]
6 for i in range(1, m + 1):
7 for j in range(1, n + 1):
8 if nums1[i - 1] == nums2[j - 1]:
9 dp[i][j] = dp[i - 1][j - 1] + 1
10 else:
11 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
12 return dp[m][n]
13
14# Example usage
15print(maxUncrossedLines([1,4,2], [1,2,4])) # Output: 2ℹ
Complexity note: The time complexity is O(m * n) because we are filling a 2D array of size m x n, where m and n are the lengths of nums1 and nums2, respectively. The space complexity is also O(m * n) due to the storage of the DP table.
- 1The problem can be visualized as finding the longest common subsequence between two arrays.
- 2Dynamic programming is a powerful technique for optimizing problems that involve making decisions based on previous results.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.