Uncrossed Lines — LeetCode 1035 Python Solution

MediumArrayDynamic Programming
Problem
#1035
Reading time
2 min

The problem

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.

Example

Input
nums1 = [1,4,2], nums2 = [1,2,4]
Output
2
Explanation
We can draw 2 uncrossed lines as in the diagram.

Python solution

Python
class Solution:
    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
        m, n = len(nums1), len(nums2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for i, x in enumerate(nums1, 1):
            for j, y in enumerate(nums2, 1):
                if x == y:
                    f[i][j] = f[i - 1][j - 1] + 1
                else:
                    f[i][j] = max(f[i - 1][j], f[i][j - 1])
        return f[m][n]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1035. Uncrossed Lines is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1035. Uncrossed Lines?
LeetCode 1035. Uncrossed Lines is rated Medium on LeetCode.
What is the time complexity of LeetCode 1035. Uncrossed Lines?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1035. Uncrossed Lines?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1035. Uncrossed Lines cover?
LeetCode 1035. Uncrossed Lines is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview