Problem 718

Abstract / Summary

Find the longest sequence of consecutive elements that appears in both arrays.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
50 lines | 1675 bytes | submitted November 24, 2023 | GitHub   20% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 3.81 | σ = 1.83

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
37 links | 22 authors | 8 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

10 solutions   November 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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