Python 1035.py
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
@cache
def deeper(posUp, posDown):
if posUp == len(nums1) or posDown == len(nums2):
return 0
# scan upper numbers
bestUp = deeper(posUp + 1, posDown)
# scan lower numbers
up = nums1[posUp]
for i in range(posDown, len(nums2)):
down = nums2[i]
if up == down:
return max(bestUp, 1 + deeper(posUp + 1, i + 1))
return bestUp
return deeper(0, 0)
Difficulty
and has an acceptance rate of about 63% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method maxUncrossedLines that computes the maximum number of non-crossing matching pairs between two integer sequences. The algorithm is expressed as a recursive depth-first search with memoization, effectively solving a dynamic programming formulation of the longest common subsequence problem. By caching intermediate results, the solution avoids redundant recomputation and achieves a tractable execution profile even for moderately sized inputs.
Core Logic
Entry Point
The public method maxUncrossedLines receives the two input lists and immediately defines a nested helper function deeper. The helper is decorated with @cache, which binds Python’s built-in memoization mechanism to the function’s arguments.
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
@cache
def deeper(posUp, posDown):
...
return deeper(0, 0)
The call deeper(0, 0) initiates the recursion at the start of both sequences.
Base Condition
The first conditional inside deeper checks whether either index has reached the end of its respective list. When this occurs, no further matches are possible, and the function returns zero.
if posUp == len(nums1) or posDown == len(nums2):
return 0
This condition gracefully handles empty input lists and the termination of recursion when one sequence is exhausted.
Skipping an Element in the Upper Sequence
The algorithm explores the option of ignoring the current element of nums1. It does so by recursively calling deeper with the upper index advanced by one while keeping the lower index unchanged. The result is stored in bestUp.
bestUp = deeper(posUp + 1, posDown)
This branch captures scenarios where the optimal solution does not involve the element at posUp.
Searching for a Matching Element in the Lower Sequence
The next segment extracts the current value from nums1 and iterates over the remaining portion of nums2 starting at posDown. For each candidate down, the code checks equality with up. Upon finding a match, it computes the candidate solution as one plus the result of recursing past both matched positions. The max function then selects the better of the previously computed bestUp and this new candidate.
up = nums1[posUp]
for i in range(posDown, len(nums2)):
down = nums2[i]
if up == down:
return max(bestUp, 1 + deeper(posUp + 1, i + 1))
The early return inside the loop ensures that once a match is found, the function does not continue scanning further lower elements for the same up. This behavior reflects the principle that the first matching position yields the optimal continuation when combined with the memoized subproblem results.
Fallback When No Match Exists
If the loop completes without encountering a matching element, the function falls back to the previously computed bestUp, effectively discarding the current up value.
return bestUp
This path handles cases where the current element of nums1 has no counterpart in the remaining segment of nums2.
Edge Cases Handled
When either input list is empty, the base condition triggers immediately, returning zero without entering the recursive logic. The loop that scans nums2 gracefully handles an empty range because range(posDown, len(nums2)) yields no iterations, causing the function to return bestUp, which itself will be zero if both lists are empty.
If the two lists contain duplicate values, the algorithm correctly distinguishes between different positions because the recursion advances both indices past the matched pair. Consequently, later occurrences of the same value are treated independently, preserving the non-crossing constraint.
When all elements of nums1 appear in nums2 in the same order, the recursion will repeatedly take the matching branch, accumulating a count equal to the length of nums1. Conversely, if the sequences are in reverse order, the algorithm will repeatedly choose the “skip upper element” branch, ultimately returning zero, which aligns with the requirement that lines must not cross.
Performance Optimizations
The primary optimization is the use of the @cache decorator on the recursive helper. By caching the result of each (posUp, posDown) pair, the algorithm eliminates exponential blow-up typical of naïve recursive solutions. Each distinct state is computed at most once, turning the overall work into a polynomial number of subproblems proportional to the product of the two list lengths.
Another subtle optimization is the early exit from the inner loop upon finding the first matching element. Because the recursive call already accounts for the optimal continuation from that point onward, there is no need to explore later matches for the same up. This reduces the number of recursive invocations and leverages the memoized results for subsequent states.
The decision to compute bestUp before scanning for matches ensures that the “skip” scenario is always available, even if a match is found later in the lower list. This ordering avoids redundant recomputation of the “skip” branch inside the loop.
Overall, the combination of memoization and strategic early returns yields an implementation that scales efficiently for typical problem sizes while maintaining clear and concise logic.
ELI5 - Simplified Explanation
Imagine two rows of colored blocks laid out on the floor. The goal is to draw straight lines between matching blocks without any of the lines crossing each other. This code works by looking at the first block in the top row and asking a little helper to decide what to do. The helper checks if that top block finds a matching block in the bottom row. If it finds a match, it draws a line and keeps going to look for more matches with the remaining blocks. If it does not find a match, or if it decides to skip that block to see if something better is ahead, it just moves to the next block in the top row. The code remembers all the different ways it has checked the lines so it never has to do the same work twice. By testing every possibility, it eventually finds the longest set of lines that can be drawn without crossing.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | JS | Go | TS | ||
| LeetcodeHelp | C++ | Python | Java | |||||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| Garvit244 | Python | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| MacJim | C++ | |||||||
| sonugiri1043 | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| vthwang | Java | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| Garvit244 | Python | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| MacJim | C++ | |||||||
| sonugiri1043 | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| vthwang | Java | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 72: Edit Distance
Solved On The Same Day
- problem 101: Symmetric Tree
- problem 337: House Robber III
- problem 790: Domino and Tromino Tiling
- problem 115: Distinct Subsequences
- problem 124: Binary Tree Maximum Path Sum
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality