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 Subarraynums1:13215nums2:32147Common Subarray [3,2,1]Green cells show the longest common subarrayMaximum Length: 3
Understanding the Visualization
1
Input Arrays
Two integer arrays nums1 and nums2
2
Find Common Subarrays
Identify all contiguous sequences that appear in both arrays
3
Return Maximum Length
Output the length of the longest common subarray
Key Takeaway
🎯 Key Insight: Use dynamic programming to efficiently track common subarray lengths at each position pair
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