You are given two integer arrays nums1
and nums2
. You need to return the maximum length of a subarray that appears in both arrays.
Input:
nums1 = [1,2,3,2,1],
nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3, 2, 1].
The problem of finding the maximum length of a subarray that appears in both arrays can be efficiently solved using dynamic programming (DP).
dp[i][j]
represent the length of the longest common subarray ending at nums1[i-1]
and nums2[j-1]
.dp
of size (len(nums1) + 1) x (len(nums2) + 1)
will be used where dp[0][*]
and dp[*][0]
are initialized to 0.(i, j)
, if nums1[i-1] == nums2[j-1]
, set dp[i][j] = dp[i-1][j-1] + 1
.dp[i][j] = 0
because the subarrays ending at those points do not match.dp[i][j]
.O(m * n)
where m
is the length of nums1
and n
is the length of nums2
.O(m * n)
for the DP table.def findLength(nums1, nums2):
m, n = len(nums1), len(nums2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_len = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if nums1[i - 1] == nums2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
max_len = max(max_len, dp[i][j])
return max_len
# Example usage:
nums1 = [1, 2, 3, 2, 1]
nums2 = [3, 2, 1, 4, 7]
print(findLength(nums1, nums2)) # Output: 3
This solution fills out the DP table based on the rules and efficiently keeps track of the maximum length of the repeated subarray.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?