Uncrossed Lines Problem
Description
LeetCode Problem 1035.
You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:
nums1[i] == nums2[j], and- the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
Example 1:

Input: nums1 = [1,4,2], nums2 = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.
Example 2:
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
Output: 2
Constraints:
1 <= nums1.length, nums2.length <= 5001 <= nums1[i], nums2[j] <= 2000
Solution
Approach: Longest Common Subsequence
Lines that do not cross must connect nums1 and nums2 in the same left-to-right order: if nums1[i] connects to nums2[j] and nums1[i'] to nums2[j'] with i < i', then j < j'. So a set of uncrossed lines is just a sequence of equal values that appears as a subsequence of both arrays, and the question is the length of their longest common subsequence.
Let f[i][j] be the most lines we can draw between the first i numbers of nums1 and the first j numbers of nums2, with f[0][j] = f[i][0] = 0. Look at the last numbers of both prefixes:
- If
nums1[i - 1] == nums2[j - 1], connect them:f[i][j] = f[i - 1][j - 1] + 1. Connecting the two last numbers never hurts, since nothing else to their right could use them. - Otherwise at least one of them stays unconnected:
f[i][j] = max(f[i - 1][j], f[i][j - 1]).
The answer is f[m][n].
Complexity: O(m * n) time and space. Since each row only uses the row before it, the space can be reduced to O(n).
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
# f[i][j]: most lines between the first i numbers of nums1 and the first j numbers of nums2
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if nums1[i - 1] == nums2[j - 1]:
f[i][j] = f[i - 1][j - 1] + 1 # connect the two last numbers
else:
f[i][j] = max(f[i - 1][j], f[i][j - 1]) # leave one of them unconnected
return f[m][n]