Uncrossed Lines (LeetCode 1035): Solution and Explanation
Two arrays are written on two parallel lines. You may connect equal numbers with straight lines, but no two lines may cross or share an endpoint. Return the most lines you can draw.
Intuition
Take two lines, one from nums1[a] to nums2[b] and one from nums1[c] to nums2[d]. They avoid each other exactly when a < c and b < d (or both reversed). So a valid drawing is a list of index pairs that increase on both sides at once.
The values along such a drawing form a sequence that appears, in order, in both arrays. That is a common subsequence, and the number of lines is its length. The problem is Longest Common Subsequence with a story on top.
Look at the last number of each prefix. If they are equal, connecting them never hurts: any line using either of them could be swapped for this one. If they differ, at least one of them is unused, so we drop it and solve a smaller pair of prefixes.
Those smaller pairs of prefixes overlap heavily, so we store them in a table dp[i][j] and fill it row by row.
Approach: LCS table over prefixes
- Create an
(m + 1) x (n + 1)tabledpof zeros. Row 0 and column 0 stand for an empty prefix, which allows no lines. - For each
ifrom 1 tomand eachjfrom 1 ton, comparenums1[i - 1]withnums2[j - 1]. - If they are equal, connect them:
dp[i][j] = dp[i - 1][j - 1] + 1. - Otherwise drop one of the two numbers:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]). - Return
dp[m][n].
Step-by-step example
nums1 = [1, 4, 2], nums2 = [1, 2, 4]
- Row 1 (top number 1): it matches the bottom 1, so dp[1][1] = 1, and the rest of the row stays 1.
- Row 2 (top number 4): 4 matches the bottom 4 at column 3, so dp[2][3] = dp[1][2] + 1 = 2.
- Row 3 (top number 2): 2 matches the bottom 2 at column 2, giving dp[3][2] = dp[2][1] + 1 = 2. dp[3][3] = max(dp[2][3], dp[3][2]) = 2.
- dp[3][3] = 2: for example lines 1-1 and 4-4. Adding 2-2 would cross 4-4.
Code: Python, Java, C++
1class Solution:
2 def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
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] = dp[i - 1][j - 1] + 1
9 else:
10 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
11 return dp[m][n]1class Solution {
2 public int maxUncrossedLines(int[] nums1, int[] nums2) {
3 int m = nums1.length, n = nums2.length;
4 int[][] dp = new int[m + 1][n + 1];
5 for (int i = 1; i <= m; i++) {
6 for (int j = 1; j <= n; j++) {
7 if (nums1[i - 1] == nums2[j - 1]) {
8 dp[i][j] = dp[i - 1][j - 1] + 1;
9 } else {
10 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
11 }
12 }
13 }
14 return dp[m][n];
15 }
16}1class Solution {
2public:
3 int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
4 int m = nums1.size(), n = nums2.size();
5 vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
6 for (int i = 1; i <= m; i++) {
7 for (int j = 1; j <= n; j++) {
8 if (nums1[i - 1] == nums2[j - 1]) {
9 dp[i][j] = dp[i - 1][j - 1] + 1;
10 } else {
11 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
12 }
13 }
14 }
15 return dp[m][n];
16 }
17};Time and space complexity
O(m * n)
Each of the m * n cells is filled once in constant time.
O(m * n)
The full table is stored. Only the previous row is ever read, so it can be reduced to O(n).
Other approaches
Two rolling rows (time O(m * n), space O(n))
Keep only the previous row and the current row of the table. The answer and the time are the same, and the memory drops to two rows.
Memoized recursion (time O(m * n), space O(m * n))
Recurse on (i, j) from the ends of the arrays with the same match or skip rule and cache results. It reads naturally but uses the recursion stack and the same O(m * n) cache.
Common mistakes
- Greedily connecting the first equal pair you find. An early line can block several later ones.
- Forgetting that lines may not share an endpoint, and connecting one number to several equal numbers on the other side.
- Off-by-one errors: dp has one extra row and column, so cell (i, j) compares nums1[i - 1] with nums2[j - 1].
- Taking max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + 1) without checking equality, which counts lines between different values.
Frequently asked questions
Why is this the same as Longest Common Subsequence?
Lines do not cross exactly when their indices increase together on both sides, which means the connected values form a sequence that appears in order in both arrays. The most lines is the longest such sequence.
When the last numbers match, why is it always safe to connect them?
Any optimal drawing can use at most one of the two for some other line. Replacing that line with the line between the two last numbers keeps everything else valid and the count the same.
Can I recover which lines to draw?
Yes. Walk back from dp[m][n]: on a match, record the pair and move diagonally; otherwise move toward the larger of the cell above and the cell to the left.