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. For example, in the array [1,2,3,4], the subarrays include [1], [2,3], [3,4], [1,2,3], etc.

The goal is to find the longest common subarray between the two given arrays.

Input & Output

Example 1 — Basic Common Subarray
$ Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
💡 Note: The longest common subarray is [3,2,1] which appears in nums1 at indices 2-4 and in nums2 at indices 0-2. Length = 3.
Example 2 — Partial Match
$ Input: nums1 = [0,0,0,0,1], nums2 = [1,0,0,0,0]
Output: 4
💡 Note: The longest common subarray is [0,0,0,0] which appears in nums1 at indices 0-3 and in nums2 at indices 1-4. Length = 4.
Example 3 — No Common Subarray
$ Input: nums1 = [1,2,3], nums2 = [4,5,6]
Output: 0
💡 Note: There are no common elements between the arrays, so the maximum length is 0.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 100

Visualization

Tap to expand
Maximum Length of Repeated Subarray INPUT nums1 1 2 3 2 1 nums2 3 2 1 4 7 Common Subarray: [3,2,1] 3 2 1 nums1 = [1,2,3,2,1] nums2 = [3,2,1,4,7] Find longest common subarray ALGORITHM STEPS (DP) 1 Create DP Table dp[i][j] = common length 2 Compare Elements If equal: dp[i][j]=dp[i-1][j-1]+1 3 Track Maximum Update max when match found 4 Return Result Maximum length found DP Table (partial) 3 2 1 4 7 1 2 3 2 1 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 Max value in table = 3 FINAL RESULT Longest Common Subarray In nums1: positions 2-4 1 2 3 2 1 In nums2: positions 0-2 3 2 1 4 7 Output 3 OK - Verified [3,2,1] appears in both Key Insight: The DP approach uses dp[i][j] to store the length of the longest common subarray ending at nums1[i-1] and nums2[j-1]. When elements match, we extend the previous diagonal value by 1. Time: O(m*n), Space: O(m*n). TutorialsPoint - Maximum Length of Repeated Subarray | Dynamic Programming Approach
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
125.0K Views
Medium Frequency
~25 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen