Maximum Length of Repeated Subarray (LeetCode 718): Solution and Explanation
Given two integer arrays, return the length of the longest contiguous block that appears in both.
Intuition
If nums1[i..i+L-1] equals nums2[j..j+L-1], then every pair in the match has the same offset i - j. A shared subarray always lives on one fixed alignment of the two arrays.
So picture nums1 written on a strip and nums2 on a second strip underneath it. Slide the bottom strip to every possible offset. At each offset, a shared subarray is just a run of columns where the top and bottom values are equal.
Counting the longest run of equal pairs on one alignment is a single pass with a counter that grows on a match and resets on a mismatch.
There are n + m - 1 alignments and each one checks at most min(n, m) pairs, so the whole scan is O(n * m) and needs no table at all.
Approach: Slide nums2 under nums1 and count equal runs
- Set
best = 0. - For every
shiftfrom-(m - 1)ton - 1, placenums2[j]undernums1[j + shift]. - Start at
i = max(shift, 0),j = i - shift, withrun = 0. - While both indices are in range: if
nums1[i] == nums2[j], add one torunand updatebest; otherwise setrun = 0. Then move both indices right. - Return
best.
Step-by-step example
nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
- Shifts -4 to -1 put nums2 mostly to the left of nums1. The best they find is a single equal pair (for example nums1[0] = nums2[2] = 1 at shift -2), so
best = 1. - Shift 0 stacks the arrays exactly: 1/3, 2/2, 3/1, 2/4, 1/7. Only the pair 2/2 matches, so
beststays 1. - Shift 2 puts nums2[0] under nums1[2]. The stacked pairs are 3/3, 2/2, 1/1, so the run grows to 1, 2, 3 and
best = 3. - Shifts 3 and 4 only overlap one or two pairs and cannot beat 3, so the answer is 3.
Code: Python, Java, C++
1class Solution:
2 def findLength(self, nums1: List[int], nums2: List[int]) -> int:
3 n, m = len(nums1), len(nums2)
4 best = 0
5 for shift in range(-(m - 1), n):
6 run = 0
7 i = max(shift, 0)
8 j = i - shift
9 while i < n and j < m:
10 if nums1[i] == nums2[j]:
11 run += 1
12 best = max(best, run)
13 else:
14 run = 0
15 i += 1
16 j += 1
17 return best1class Solution {
2 public int findLength(int[] nums1, int[] nums2) {
3 int n = nums1.length, m = nums2.length;
4 int best = 0;
5 for (int shift = -(m - 1); shift < n; shift++) {
6 int run = 0;
7 int i = Math.max(shift, 0), j = i - shift;
8 for (; i < n && j < m; i++, j++) {
9 if (nums1[i] == nums2[j]) {
10 run++;
11 best = Math.max(best, run);
12 } else {
13 run = 0;
14 }
15 }
16 }
17 return best;
18 }
19}1class Solution {
2public:
3 int findLength(vector<int>& nums1, vector<int>& nums2) {
4 int n = nums1.size(), m = nums2.size();
5 int best = 0;
6 for (int shift = -(m - 1); shift < n; shift++) {
7 int run = 0;
8 int i = max(shift, 0), j = i - shift;
9 for (; i < n && j < m; i++, j++) {
10 if (nums1[i] == nums2[j]) {
11 run++;
12 best = max(best, run);
13 } else {
14 run = 0;
15 }
16 }
17 }
18 return best;
19 }
20};Time and space complexity
O(n * m)
Every pair (i, j) lies on exactly one alignment, so the inner loop runs n * m times in total.
O(1)
Only the shift, the two indices, the run counter and the best length are stored.
Other approaches
Dynamic programming table (time O(n * m), space O(m))
Let dp[i][j] be the length of the common run ending at nums1[i-1] and nums2[j-1]. It is dp[i-1][j-1] + 1 on equal values and 0 otherwise. A single row of the table is enough if you fill it right to left.
Binary search on length with rolling hash (time O((n + m) log(min(n, m))), space O(n))
If a shared block of length L exists, so does one of length L - 1. Binary search L and check each guess by hashing every window of nums1 into a set and looking up the windows of nums2.
Compare every pair of start positions (time O(n * m * min(n, m)), space O(1))
For each i and j, extend while the values match. Simple but cubic in the worst case, such as two arrays of all zeros.
Common mistakes
- Confusing a subarray with a subsequence. The shared block must be contiguous, so a mismatch resets the run to 0 instead of skipping ahead.
- Only sliding in one direction. You need shifts where nums2 starts left of nums1 as well as right of it, so the range is -(m - 1) to n - 1.
- Forgetting to reset
runat the start of every alignment, which lets a run leak from one shift into the next. - In the DP version, filling a single row left to right overwrites dp[j-1] before it is read. Go right to left or keep two rows.
Frequently asked questions
Why does fixing the offset work?
Inside a shared block, both indices move right together, so i - j never changes. Every possible answer lives on exactly one alignment, and checking all alignments checks all possible answers.
Is this the same as the DP solution?
Yes. Each alignment is one diagonal of the DP table, and the run counter is the value of dp along that diagonal. Walking diagonals just avoids storing the table.
How is this different from Longest Common Subsequence?
Longest Common Subsequence may skip elements, so a mismatch keeps the best of two neighbors. Here a mismatch breaks the block, so the run drops to 0.
Can it be faster than O(n * m)?
Binary searching the length with a rolling hash brings it to about O((n + m) log n), at the cost of hashing code and a small chance of collisions that must be double checked.