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.

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
Uncrossed Lines - Dynamic Programming INPUT nums1 = [1, 4, 2] 1 4 2 i=0 i=1 i=2 nums2 = [1, 2, 4] 1 2 4 j=0 j=1 j=2 Valid connection Would cross Find max uncrossed lines ALGORITHM STEPS 1 Create DP Table dp[i][j] = max lines for nums1[0..i], nums2[0..j] 2 If nums1[i]==nums2[j] dp[i][j] = dp[i-1][j-1] + 1 3 Otherwise dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 4 Return dp[m][n] Answer at bottom-right DP Table: "" 1 2 4 "" 0 0 0 0 1 0 1 1 1 4 0 1 1 2 2 0 1 2 2 FINAL RESULT Maximum Uncrossed Lines 1 4 2 1 2 4 Connect 1--1 and 4--4 These lines do not cross! Output: 2 OK - 2 uncrossed lines Time: O(m*n), Space: O(m*n) Key Insight: This problem is equivalent to finding the Longest Common Subsequence (LCS) of two arrays. Non-crossing constraint naturally maps to preserving order - same as LCS property! dp[i][j] represents max connections using first i elements of nums1 and first j of nums2. TutorialsPoint - Uncrossed Lines | Dynamic Programming Approach
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