Uncrossed Lines - Problem
Uncrossed Lines is a fascinating dynamic programming challenge that visualizes connections between two sequences.
Given two integer arrays
• No crossing lines: Any two connecting lines cannot intersect
• One connection per number: Each number can only be used in one connecting line
• Order preservation: Lines must maintain the relative ordering of elements
Return the maximum number of connecting lines you can draw. This problem is essentially finding the Longest Common Subsequence (LCS) between two arrays!
Given two integer arrays
nums1 and nums2, imagine writing the numbers from nums1 on a horizontal line and the numbers from nums2 on another horizontal line below it. Your goal is to draw straight connecting lines between matching numbers (where nums1[i] == nums2[j]) with the following constraints:• No crossing lines: Any two connecting lines cannot intersect
• One connection per number: Each number can only be used in one connecting line
• Order preservation: Lines must maintain the relative ordering of elements
Return the maximum number of connecting lines you can draw. This problem is essentially finding the Longest Common Subsequence (LCS) between two arrays!
Input & Output
example_1.py — Basic Case
$
Input:
nums1 = [1,4,2], nums2 = [1,2,4]
›
Output:
2
💡 Note:
We can draw 2 uncrossed lines: connect the 1s and connect 2 in nums1 to 2 in nums2. We cannot connect 4s because it would cross the line connecting the 2s.
example_2.py — No Common Elements
$
Input:
nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
›
Output:
3
💡 Note:
We can connect three pairs: (5,5), (1,1), and (2,2). The optimal strategy is to find the longest common subsequence while maintaining order.
example_3.py — Single Elements
$
Input:
nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
›
Output:
2
💡 Note:
We can connect (1,1) and (5,5). Even though there are multiple 1s, we can only use each position once to avoid crossing.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 500
- 1 ≤ nums1[i], nums2[j] ≤ 2000
- No crossing lines allowed
- Each number can be used at most once
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code