Maximum Length of Repeated Subarray

Medium Advanced data structures and strings AI round

nums1 and nums2 are two lists of whole numbers.

A subarray is a stretch of a list taken without gaps, at least one number long. A subarray is shared when the same numbers, in the same order, are a subarray of both lists.

Return the length of the longest shared subarray, or 0 if the two lists have no number in common.

Example 1

Input: nums1 = [3,9,5,2,7,6], nums2 = [9,5,3,2,7,6]
Output: 3

[2, 7, 6] is a subarray of both lists. 9, 5, 2, 7, 6 appear in both in that order too, but in nums2 a 3 sits between the 5 and the 2, so they are not one stretch there.

Example 2

Input: nums1 = [5,5,5,8], nums2 = [5,5]
Output: 2

Example 3

Input: nums1 = [1,2], nums2 = [-1,-2]
Output: 0

No number is in both lists.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 3000
  • -100 ≤ nums1[i], nums2[j] ≤ 100

Watch the explanation

More Advanced data structures and strings

All Advanced data structures and strings problems