718 Maximum Length of Repeated Subarray
Last updated
Last updated
Given two integer arraysA
andB
, return the maximum length of an subarray that appears in both arrays.
Example 1:
Note:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
The Idea: First lets try to identify where the numbers within the array actually match. The first combination where they do match marks what may potentially begin as the longest maximum length of the two arrays. Once this is done, we need to identify the longest path. The way to do this can be done in two particular ways. Either we can count forwards A(3,2,1) -> B(3,2,1)
or we can count backwards A(1,2,3) -> B(1,2,3)
. Because we will be iterating through the elements of arrays A and B, it is more natural to count forwards. Once we confirm a matching region in A that is also in B, how can be confirm that the previous position also matched? Well consider the example when we match (3,2) (elements 2 in indicies 3, and 2 in A and B respectfully). The elements that came before it are 2 and 1 (just -1 from there previous indices). So in the matrix, for we look at the upper left cell, we can identify whether the previous element matched. Eventually we can accumulate this among itself and basically maintain the total number of match elements so far. Then maximum element in the matrix will hence represent the length of the longest common subarray.
Complexity: O(n*m) time and space