LeetCode #1035 Medium

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.

Constraints
  • 1 <= nums1.length, nums2.length <= 500
  • 1 <= nums1[i], nums2[j] <= 2000
arraydynamic-programming
Open on LeetCode ↗
02

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).

How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maxUncrossedLines(self, nums1, nums2):
▶3 m, n = len(nums1), len(nums2)
▶4 dp = [[0] * (n + 1) for _ in range(m + 1)]
▶5 for i in range(1, m + 1):
▶6 for j in range(1, n + 1):
▶7 if nums1[i - 1] == nums2[j - 1]:
▶8 dp[i][j] = 1 + dp[i - 1][j - 1]
▶9 else:
▶10 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
▶11 return dp[m][n]
nums1nums2011422102142best lines–124–0000104020empty prefixes hold 0 lines
m3numbers in nums1
n3numbers in nums2
Each table cell will hold the most lines that fit between the first few numbers of nums1 (its row) and the first few of nums2 (its column). The top row and left column stand for an empty prefix, which has nothing to connect, so they are 0.
nums1nums2011422102142best lines–124–00001014020both end in 1 → draw it, 1 line
nums1[0]1
nums2[0]1
dp[1][1]1
The last numbers of both prefixes are 1. A line between them lies right of every earlier line, so it crosses nothing: the count is 1 plus the up-left cell, 1. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–0000101140201 and 2 differ → keep 1 from the left
nums1[0]1
nums2[1]2
dp[1][2]1
1 and 2 cannot be joined, and at most one of them can have a line in a best answer, so drop one. Dropping the 1 leaves 0, dropping the 2 leaves 1; keep 1. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–00001011140201 and 4 differ → keep 1 from the left
nums1[0]1
nums2[2]4
dp[1][3]1
1 and 4 cannot be joined, and at most one of them can have a line in a best answer, so drop one. Dropping the 1 leaves 0, dropping the 4 leaves 1; keep 1. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–000010111401204 and 1 differ → keep 1 from above
nums1[1]4
nums2[0]1
dp[2][1]1
4 and 1 cannot be joined, and at most one of them can have a line in a best answer, so drop one. Dropping the 4 leaves 1, dropping the 1 leaves 0; keep 1. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–0000101114011204 and 2 differ → keep 1
nums1[1]4
nums2[1]2
dp[2][2]1
4 and 2 cannot be joined, and at most one of them can have a line in a best answer, so drop one. Dropping the 4 leaves 1, dropping the 2 leaves 1; keep 1. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–0000101114011220both end in 4 → draw it, 2 lines
nums1[1]4
nums2[2]4
dp[2][3]2
The last numbers of both prefixes are 4. A line between them lies right of every earlier line, so it crosses nothing: the count is 1 plus the up-left cell, 2. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–000010111401122012 and 1 differ → keep 1 from above
nums1[2]2
nums2[0]1
dp[3][1]1
2 and 1 cannot be joined, and at most one of them can have a line in a best answer, so drop one. Dropping the 2 leaves 1, dropping the 1 leaves 0; keep 1. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–000010111401122012both end in 2 → draw it, 2 lines
nums1[2]2
nums2[1]2
dp[3][2]2
The last numbers of both prefixes are 2. A line between them lies right of every earlier line, so it crosses nothing: the count is 1 plus the up-left cell, 2. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–00001011140112201222 and 4 differ → keep 2
nums1[2]2
nums2[2]4
dp[3][3]2
2 and 4 cannot be joined, and at most one of them can have a line in a best answer, so drop one. Dropping the 2 leaves 2, dropping the 4 leaves 2; keep 2. The lines drawn above are one best set for these two prefixes.
nums1nums2011422102142best lines–124–0000101114011220122answer: 2 lines
dp[3][3]2both arrays in full
The bottom-right cell covers both whole arrays, so the answer is 2. The green lines are one set that reaches it; read from left to right, they join 1, 4, a sequence found in the same order in both arrays. The dashed red line joins a shared value that is left out: it would cross a green line, so adding it is not allowed.
05

Common pitfalls

Counting shared values

✗ Wrong
return len(set(nums1) & set(nums2))
✓ Right
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

✗ Wrong
if nums1[i] == nums2[j]:
✓ Right
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

✗ Wrong
for j in range(1, n + 1):
    if nums1[i - 1] == nums2[j - 1]:
        dp[j] = 1 + dp[j - 1]
✓ Right
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 = old

In 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.

06

Edge cases

No number appears in both arrays

No cell ever takes the match branch, so every cell is the max of zeros and the answer is 0.

One number repeated on one side, e.g. [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.

07

Complexity

Time
O(m · n)
Space
O(m · n)
Each of the m · n cells is filled once in O(1). Each row reads only the row above it, so keeping two rows of length min(m, n) + 1 cuts the space to O(min(m, n)).
08

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.