Maximum Length of Repeated Subarray
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #718
Return the maximum length of a subarray that appears in both arrays. A subarray is contiguous.
Examples
text
nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] → 3 ([3,2,1])
nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] → 5Hints
- Contiguous means it's a common substring, not a subsequence. A mismatch resets the length to 0.
Approach
dp[i][j] = the length of the longest common suffix of nums1[:i] and nums2[:j]. If the elements match, it's dp[i−1][j−1] + 1, otherwise 0. Track the max.
Iterate j backwards to roll it into 1-D, so that dp[j−1] still holds the previous row's value. That's O(m·n) time and O(n) space. Binary search on the length + rolling hash gives O((m+n) log min(m,n)) for large inputs.
Compare with LCS (subsequence): there a mismatch takes max(top, left) instead of resetting.
Complexity
Time: O(m·n). Space: O(n).
Python solution
def findLength(nums1, nums2):
n = len(nums2)
dp = [0] * (n + 1)
best = 0
for a in nums1:
for j in range(n, 0, -1):
if a == nums2[j - 1]:
dp[j] = dp[j - 1] + 1
best = max(best, dp[j])
else:
dp[j] = 0
return bestJavaScript solution
function findLength(nums1, nums2) {
const n = nums2.length, dp = new Array(n + 1).fill(0);
let best = 0;
for (const a of nums1) for (let j = n; j >= 1; j--) {
dp[j] = a === nums2[j - 1] ? dp[j - 1] + 1 : 0;
best = Math.max(best, dp[j]);
}
return best;
}