Skip to content
Advertisement

Maximum Length of Repeated Subarray (leetcode)

I’m looking at this leetcode question, and am having an issue completing the naive approach. I was able to come to an optimal solution here. But I’m not sure what’s wrong with my naive attempt.

The question is as follows:

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

Example:
Input: A: [1,2,3,2,1] B: [3,2,1,4,7]

Output: 3

Explanation: The repeated subarray with maximum length is [3, 2, 1].

Here is my current code:

JavaScript

My solution passes several test cases, but fails on cases like a: [0,1,1,1,1] b: [1,0,1,0,1]. Any insight on my mistake would be appreciated!

Advertisement

Answer

The problem comes from the way you calculate the max length when the last elements match. here is a minimal example:

JavaScript

If there is any match you add 1 to the max length but that’s not necessarily true if there is a mismatch later. Here is a shortened version what happens with illustration for easier understanding:

JavaScript

When you total all the matches, you get 3 however, the count should have been reset when there was a mismatch.

One simple change that can be done to the algorithm to avoid this problem is to pass the current count as an argument to the function. This way, you can control when the count needs to be reset:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement