Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
A subarray is a contiguous sequence of elements within an array.
Function Signature
def find_length(nums1: list[int], nums2: list[int]) -> int:
Rules
-
The shared subarray must be contiguous in both arrays, with the same values in the same order. It may start at different positions in the two arrays.
-
If no value appears in both arrays, return
0
.
Constraints
-
1 <= nums1.length, nums2.length <= 1000
-
0 <= nums1[i], nums2[i] <= 100
Examples
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
The subarray [3,2,1] occupies indices 2 to 4 of nums1 and indices 0 to 2 of nums2. No longer run is shared, because every length-4 window of nums2 contains a 4, which never appears in nums1.
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
The arrays are identical, so the whole array [0,0,0,0,0] is shared.
Input: nums1 = [1,2,3,4], nums2 = [1,3,2,4]
Output: 1
Every value appears in both arrays, but none of the pairs [1,2], [2,3], [3,4] occurs in nums2, so the longest shared subarray is a single element. A common subsequence such as [1,2,4] does not count, since it is not contiguous.