Problem
Given two integer arraysnums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Examples
Constraints
- 1 <= nums1.length, nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 718 with 24 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 718 # by problem number
lcpy gen -s maximum_length_of_repeated_subarray # by problem name
nums1 and nums2, 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].
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
Explanation: The repeated subarray with maximum length is [0,0,0,0,0].
class Solution:
# Time: O(len(nums1) * len(nums2))
# Space: O(len(nums2))
def find_length(self, nums1: list[int], nums2: list[int]) -> int:
best = 0
prev = [0] * (len(nums2) + 1)
for a in nums1:
cur = [0] * (len(nums2) + 1)
for j, b in enumerate(nums2, start=1):
if a == b:
cur[j] = prev[j - 1] + 1
if cur[j] > best:
best = cur[j]
prev = cur
return best
| Time | Space |
|---|---|
| O(len(nums1) * len(nums2)) | O(len(nums2)) |