oneby7

2-D Dynamic Programming Two strings

559. Maximum Length of Repeated Subarray

Medium

You are given two arrays of integers, nums1 and nums2. Return the length of the longest subarray that appears in both of them.

A subarray is a run of elements that sit next to each other. [2,7,1] is a subarray of [4,2,7,1,9], but [2,1] is not, because the 7 sits between the 2 and the 1. The two copies of the subarray may start at different indexes.

If no value appears in both arrays, the answer is 0.

Example 1

Input: nums1 = [4, 2, 7, 7, 1, 9, 3] nums2 = [7, 1, 9, 3, 2, 4, 2, 7]

Output: 4

Explanation: [7,1,9,3] is a subarray of both: it starts at index 3 of nums1 and at index 0 of nums2. [4,2,7] is common too, but shorter.

Example 2

Input: nums1 = [0, 0, 0, 0], nums2 = [0, 0]

Output: 2

Explanation: All of nums2 is a subarray of nums1, and no common subarray can be longer than nums2.

Example 3

Input: nums1 = [1, 2, 3], nums2 = [4, 5, 6]

Output: 0

Explanation: The arrays share no value, so they have no common subarray.

Check your understanding

Work out the answer for this input before you write any code.

nums1 = [5, 8, 1, 8, 5], nums2 = [8, 5, 8, 1, 5]

Constraints

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

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.