Maximum Length of Repeated Subarray - Problem
Maximum Length of Repeated Subarray
Given two integer arrays
A subarray is a contiguous sequence of elements within an array. For example, in array
Your task is to find the longest such common subarray and return its length. If no common subarray exists, return
Example:
If
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
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
โ Linear Growth
Space Complexity
O(n ร m)
2D DP table storing results for all position combinations
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code