Python 0718.py
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
# let's try it without Longest Common Sequence algorithm
# which requires quite a significant amount of memory (len(nums1) * len(nums2)
result = 0
def fnv(hash_, value):
# FNV hash, 32 bit
return ((hash_ ^ value) * 16777619) & 0xFFFFFFFF
hash1 = nums1.copy()
hash2 = nums2.copy()
x = 0
size = min(len(nums1), len(nums2))
for length in range(1, size + 1):
shared = set(hash1) & set(hash2)
if not shared:
break
# exclude hash collisions
found = False
for i, h1 in enumerate(hash1):
if h1 in shared:
for j, h2 in enumerate(hash2):
if h2 == h1:
x += 1
if nums1[i : i + length] == nums2[j : j + length]:
found = True
result = length
break
# no collision, match was verified
if found:
break
# no matching strings
if not found:
break
# update hashes
hash1.pop()
hash2.pop()
for i in range(len(nums1) - length):
hash1[i] = fnv(hash1[i], nums1[i + length])
for i in range(len(nums2) - length):
hash2[i] = fnv(hash2[i], nums2[i + length])
return result
Difficulty
and has an acceptance rate of about 51% (700k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Dynamic Programming
- Hash Function
- Rolling Hash
- Sliding Window
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 solves the problem of finding the maximum length of a common sub-array between two integer lists. Instead of employing the classic dynamic programming approach for the longest common subsequence, it relies on a rolling hash technique inspired by the FNV hash function. By iteratively increasing the candidate length and comparing hashed windows, the algorithm narrows down the answer while avoiding the quadratic memory consumption of a full DP table. Early termination is triggered when no hash overlap exists, which prevents unnecessary work for disjoint inputs.
Key Steps
The algorithm begins by initializing the result accumulator and defining a small helper that computes a 32-bit FNV hash for a given value.
result = 0
def fnv(hash_, value):
# FNV hash, 32 bit
return ((hash_ ^ value) * 16777619) & 0xFFFFFFFF
Two mutable copies of the input lists are created. These copies will hold the rolling hash values for the current window length.
hash1 = nums1.copy()
hash2 = nums2.copy()
The outer loop iterates over possible sub-array lengths from 1 up to the size of the shorter list. For each length, the algorithm builds a set intersection of the current hash windows to quickly identify any potential matches.
size = min(len(nums1), len(nums2))
for length in range(1, size + 1):
shared = set(hash1) & set(hash2)
if not shared:
break
If a shared hash exists, the code scans the hash arrays to locate matching positions. When a hash collision is detected, the actual sub-arrays are compared element-wise to confirm the match. Upon a successful verification, the result is updated to the current length and the inner search stops.
found = False
for i, h1 in enumerate(hash1):
if h1 in shared:
for j, h2 in enumerate(hash2):
if h2 == h1:
x += 1
if nums1[i : i + length] == nums2[j : j + length]:
found = True
result = length
break
if found:
break
If no verified match is found for the current length, the outer loop terminates because longer windows cannot be common.
if not found:
break
When a match is confirmed, the hash windows are prepared for the next length. The last element of each hash list is removed, and the remaining entries are updated by feeding the next element of the original list into the FNV function, thereby rolling the hash forward.
hash1.pop()
hash2.pop()
for i in range(len(nums1) - length):
hash1[i] = fnv(hash1[i], nums1[i + length])
for i in range(len(nums2) - length):
hash2[i] = fnv(hash2[i], nums2[i + length])
Finally, the accumulated result is returned.
return result
Edge Cases
The implementation gracefully handles empty input lists. Since size becomes zero, the outer loop never executes and the initial result of zero is returned, indicating no common sub-array.
When the two lists have different lengths, the algorithm limits the search to the length of the shorter list, ensuring that window extraction never exceeds the bounds of either list.
Hash collisions are explicitly addressed. Even if two different sub-arrays produce the same hash value, the subsequent slice comparison (nums1[i : i + length] == nums2[j : j + length]) validates the actual content before accepting a match. This guarantees correctness despite the probabilistic nature of hashing.
If at any iteration the set intersection yields an empty set, the algorithm concludes that no further common sub-arrays of greater length can exist and exits early. This covers scenarios where the lists share no elements or where shared elements are positioned such that longer windows cannot align.
Performance Optimizations
The core optimization stems from the rolling hash mechanism. By updating hash values in place rather than recomputing them from scratch for each window, the algorithm reduces the amount of work required to examine successive lengths.
Using a set intersection (shared = set(hash1) & set(hash2)) provides a fast way to detect any potential overlap before diving into nested loops. This cheap pre-filter eliminates many unnecessary element-wise comparisons.
Early termination conditions-both the empty intersection check and the found flag-prevent the algorithm from continuing once it is impossible to improve the result. This avoids wasteful iterations especially for inputs with limited commonality.
The removal of the last element from each hash list (pop()) shrinks the working set as the length grows, which reduces the number of hash updates performed in subsequent iterations.
By limiting the outer loop to the minimum length of the two input lists, the algorithm avoids exploring window sizes that could never be valid, thereby bounding the total number of iterations.
ELI5 - Simplified Explanation
Imagine having two long trains made of colorful blocks. Some of the patterns of blocks in the first train might be exactly the same as the patterns in the second train. This code is like a game to find the longest matching set of blocks that appear in both trains at the same time.
First, the code calculates a special secret code for different groups of blocks. Think of it like giving a sticky note to each block that tells you what color follows it. When the code looks at the trains, it checks if any of these secret codes are the same. If they are, it means there is a chance that a chunk of the train is a perfect match.
Because the computer is very careful, it does not just trust the secret code. Once it thinks it found a match, it zooms in to look at the actual blocks to make sure they are really in the same order. It keeps doing this by checking shorter patterns and then longer patterns, slowly sliding through the trains. If it sees that a long chunk matches, it remembers how many blocks are in that chunk. Every time it finishes checking one length, it updates the secret codes to look at the next part of the trains until there are no pieces left to compare.
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | JS | Python | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fengvyi | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | 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 | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fengvyi | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 209: Minimum Size Subarray Sum
- problem 1923: Longest Common Subpath
- problem 3176: Find the Maximum Length of a Good Subsequence I
- problem 3177: Find the Maximum Length of a Good Subsequence II
Solved On The Same Day
- problem 2529: Maximum Count of Positive Integer and Negative Integer
- problem 532: K-diff Pairs in an Array
- problem 826: Most Profit Assigning Work
- problem 1237: Find Positive Integer Solution for a Given Equation
- problem 1283: Find the Smallest Divisor Given a Threshold
- problem 1552: Magnetic Force Between Two Balls
- problem 1561: Maximum Number of Coins You Can Get
- problem 1760: Minimum Limit of Balls in a Bag
- problem 1870: Minimum Speed to Arrive on Time
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