Skip to problem
←

Maximum Length of Repeated Subarray

Medium 0 attempts

You're given two integer arrays, nums1 and nums2. Find the length of the longest contiguous run of elements that shows up identically in both arrays, in the same order.

The matching run must be contiguous in both arrays; you cannot skip or rearrange elements. It may start at different indices. Return its length, not the subarray itself, and return 0 if the arrays share no element.

In Example 1, [3,2,1] occurs at indices 2–4 in nums1 and 0–2 in nums2, giving length 3.

Function contract

Implement maximumLengthOfRepeatedSubarray(nums1, nums2). Receive two nonempty integer arrays.

Output: Return the length of the longest contiguous subarray present in both arrays, or 0 if no element matches.

Example 1

Input
nums1 = [1,2,3,2,1]
nums2 = [3,2,1,4,7]
Output
3

Example 2

Input
nums1 = [0,0]
nums2 = [0]
Output
1
Constraints
  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 100

Approach: Rolling Dynamic Programming

For each element of the first array, dp[j] records the length of the matching run ending at that element and at position j - 1 of the second array. Matching values extend the previous row's diagonal by one; a mismatch resets the run to zero.

Update columns from right to left so dp[j - 1] still belongs to the previous row. Track the maximum over all positions, since the best run need not end at either array's final element. Use the shorter array for the DP columns to reduce memory.

javascript
function maximumLengthOfRepeatedSubarray(nums1, nums2) {
  if (nums1.length < nums2.length) [nums1, nums2] = [nums2, nums1];
  const dp = new Array(nums2.length + 1).fill(0);
  let best = 0;
  for (const value of nums1) {
    for (let j = nums2.length; j >= 1; j--) {
      dp[j] = value === nums2[j - 1] ? dp[j - 1] + 1 : 0;
      best = Math.max(best, dp[j]);
    }
  }
  return best;
}

Time Complexity: O(m × n), where m and n are the input lengths.

Space Complexity: O(min(m, n)) auxiliary space. Neither input array is modified.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript