Uncrossed Lines - Problem
Uncrossed Lines is a fascinating dynamic programming challenge that visualizes connections between two sequences.

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.

Visualization

Tap to expand
Street A: nums1 = [1, 4, 2]Street B: nums2 = [1, 2, 4]142124Maximum Uncrossed Connections: 2Green lines don't cross ✓ | Red dashed line would cross ✗
Understanding the Visualization
1
Layout the Streets
Place nums1 houses on top street, nums2 houses on bottom street
2
Find Matching Houses
Identify houses with same numbers that could be connected
3
Connect Without Crossing
Draw cables between matching houses ensuring no crossings
4
Maximize Connections
Use DP to find the optimal set of non-crossing connections
Key Takeaway
🎯 Key Insight: This is the Longest Common Subsequence problem in disguise! Uncrossed lines preserve order, just like LCS preserves the relative ordering of common elements.

Time & Space Complexity

Time Complexity
⏱️
O(m*n)

We fill each cell of the m×n table exactly once

n
2n
Linear Growth
Space Complexity
O(m*n)

We store the entire 2D DP table

n
2n
Linearithmic Space

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
Asked in
Google 42 Amazon 35 Microsoft 28 Apple 18
67.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen