Uncrossed Lines
Uncrossed Lines is LeetCode 1035 (Medium). The numbers of nums1 are written on one horizontal line and the numbers of nums2 on a second line below it. You may draw a straight line from nums1[i] to nums2[j] when:
- the two numbers are equal,
- the new line crosses no other line, and
- each number is the end of at most one line, so lines cannot even touch.
Return the largest number of lines you can draw. Each array holds at most 500 numbers, so a table of 500 × 500 cells is fast, while trying every set of lines is not.
- 1 <= nums1.length, nums2.length <= 500
- 1 <= nums1[i], nums2[j] <= 2000
Intuition
Two lines (i, j) and (k, l) cross exactly when their order flips: i < k but j > l. So a set of lines that never cross joins equal numbers in the same left-to-right order on both arrays.
Read the joined numbers from left to right and you get a sequence that appears, in order, in both arrays: a common subsequence. It also works the other way: any common subsequence can be drawn as lines that do not cross.
So the most lines you can draw is the length of the longest common subsequence of the two arrays, and the classic LCS table computes it in O(m · n).
Pairs that must keep their relative order in two sequences, whether described as lines that may not cross, bridges that may not overlap or matches that must stay in sequence, are a longest common subsequence in disguise.
Approach
Before reading on, draw two lines that cross and write down their index pairs. What has to be true about the pairs of two lines that do not cross? Which classic problem does that rule describe? Aim for O(m · n).
Define the table
Let dp[i][j] be the most lines you can draw using only the first i numbers of nums1 and the first j numbers of nums2. Row 0 and column 0 stay 0, because an empty prefix has nothing to connect, and this padding removes any special case for the first row.
Equal last numbers: draw the line
If nums1[i - 1] == nums2[j - 1], set dp[i][j] = 1 + dp[i - 1][j - 1]. These two numbers are the rightmost of each prefix, so a line between them lies to the right of every line counted in dp[i - 1][j - 1] and cannot cross any of them.
Why drawing that line is never a mistake
Take any best set of lines that skips this pair. At most one of the two numbers is used, because if both were joined to earlier numbers, those two lines would cross. Swap that one line for the new one: the count stays the same and nothing crosses, so some best answer always uses the match.
Different last numbers: drop one of them
Otherwise set dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]). The two numbers cannot be joined to each other, and at most one of them has a line in a best set, because if both had lines to earlier numbers, those two lines would cross. So the other can be dropped, and you keep whichever drop leaves more lines.
Fill row by row and read the corner
Loop i from 1 to m and j from 1 to n. Each cell reads only the cells above, to the left and up-left, which are already filled. dp[m][n] covers both whole arrays, so it is the answer.
Code in Python, C++ and Java
Common pitfalls
Counting shared values
return len(set(nums1) & set(nums2))
dp[i][j] = 1 + dp[i - 1][j - 1] # only for the last numbers of both prefixes
A set ignores order. For nums1 = [1, 2] and nums2 = [2, 1] it returns 2, but the line 1–1 and the line 2–2 cross, so only 1 line fits.
Comparing with table indices
if nums1[i] == nums2[j]:
if nums1[i - 1] == nums2[j - 1]:
Row i of the padded table stands for the first i numbers, whose last one is nums1[i - 1]. Using nums1[i] skips the first number and reads past the end when i = m, so even [1] and [1] throws an index error.
One-row table that loses the diagonal
for j in range(1, n + 1):
if nums1[i - 1] == nums2[j - 1]:
dp[j] = 1 + dp[j - 1]prev = 0
for j in range(1, n + 1):
old = dp[j]
if nums1[i - 1] == nums2[j - 1]:
dp[j] = 1 + prev
else:
dp[j] = max(dp[j], dp[j - 1])
prev = oldIn a single row, dp[j - 1] was already overwritten with this row's value, not the up-left value. For nums1 = [1] and nums2 = [1, 1] the wrong loop returns 2, using the one 1 of nums1 twice; the answer is 1.
Edge cases
No cell ever takes the match branch, so every cell is the max of zeros and the answer is 0.
[2, 2, 2] and [2]Every 2 of nums1 could join the single 2, but the match step uses one number from each side, so the answer is 1.
Complexity
min(m, n) + 1 cuts the space to O(min(m, n)).Uncrossed Lines FAQ
Is Uncrossed Lines the same as Longest Common Subsequence?
Yes. The answer always equals the LCS length, and LeetCode 1143 code passes once it takes two integer arrays instead of two strings. Delete Operation for Two Strings (LeetCode 583) is the same table again: it returns m + n - 2 · LCS.
Can it be solved faster than O(m · n)?
In the worst case, not by much: no known method is much faster than m · n. When few pairs of equal numbers exist, the Hunt–Szymanski method runs in about O((r + n) log n), where r is the number of equal pairs, but at 500 numbers per array the plain table already runs instantly.