Maximum Length of Repeated Subarray

Given two integer arrays nums1 and nums2, find the maximum length of a contiguous subarray that appears in both arrays.

A subarray is a contiguous sequence of elements within an array. For example, in array [1,2,3,4], the subarrays include [1,2], [2,3,4], but not [1,3] since it's not contiguous.

Your task is to find the longest such common subarray and return its length. If no common subarray exists, return 0.

Example:
If nums1 = [1,2,3,2,1] and nums2 = [3,2,1,4,7], the longest common subarray is [3,2,1] with length 3.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
โ€บ Output: 3
๐Ÿ’ก Note: The repeated subarray with maximum length is [3,2,1], which appears at indices [2,3,4] in nums1 and [0,1,2] in nums2.
example_2.py โ€” No Common Subarray
$ Input: nums1 = [1,2,3], nums2 = [4,5,6]
โ€บ Output: 0
๐Ÿ’ก Note: There are no common elements between the arrays, so no common subarray exists.
example_3.py โ€” Single Element Match
$ Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
โ€บ Output: 5
๐Ÿ’ก Note: Both arrays are identical, so the entire array [0,0,0,0,0] is the longest common subarray with length 5.

Visualization

Tap to expand
Maximum Length of Repeated Subarray - DP VisualizationDNA Strand 1: [1, 2, 3, 2, 1]DNA Strand 2: [3, 2, 1, 4, 7]DP Table123Longest match: [3,2,1]Result3๐Ÿ’ก Key Insight: When elements match, the common subarray length is 1 + length from previous diagonal position๐ŸŽฏ Time: O(nร—m) | Space: O(nร—m) | Optimal for this problem type
Understanding the Visualization
1
Setup Comparison Grid
Create a table to track matching lengths at each position pair
2
Fill Matching Positions
When elements match, extend the previous diagonal match by 1
3
Track Maximum Length
Keep track of the longest sequence found so far
4
Return Result
The maximum value represents the longest common subarray
Key Takeaway
๐ŸŽฏ Key Insight: Dynamic Programming transforms the problem from checking all possible subarray pairs O(nยฒm) into a single pass through a comparison table O(nm), leveraging the fact that matching subarrays can be extended from previous matches.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n ร— m)

Single pass through both arrays, checking each position pair once

n
2n
โœ“ Linear Growth
Space Complexity
O(n ร— m)

2D DP table storing results for all position combinations

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 1000
  • 0 โ‰ค nums1[i], nums2[i] โ‰ค 100
  • Follow up: Optimize to use only O(min(m,n)) space
Asked in
Google 42 Amazon 35 Facebook 28 Microsoft 22
67.2K Views
High Frequency
~22 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen