Finding maximum length of common subarray in JavaScript


Problem

We are required to write a JavaScript function that takes in two arrays of literals, arr1 and arr2, as the first and the second argument respectively.

Our function is supposed to return the maximum length of a subarray that appears in both arrays.

For example, if the input to the function is

Input

const arr1 = [1, 2, 3, 2, 1];
const arr2 = [3, 2, 1, 4, 7];

Output

const output = 3;

Output Explanation

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

Example

Following is the code −

 Live Demo

const arr1 = [1, 2, 3, 2, 1];
const arr2 = [3, 2, 1, 4, 7];
const maximumLength = (arr1 = [], arr2 = []) => {
   const dp = new Array(arr1.length + 1).fill(0).map(() => new Array(arr2.length + 1).fill(0))
   for (let i = arr1.length - 1; i >= 0; i--) {
      for (let j = arr2.length - 1; j >= 0; j--) {
         if (arr1[i] === arr2[j]) {
            dp[i][j] = dp[i + 1][j + 1] + 1
         } else {
            dp[i][j] = 0
         }
      }
   };
   return dp.reduce((acc, items) => Math.max(acc, ...items), 0)
}
console.log(maximumLength(arr1, arr2));

Output

3

Updated on: 24-Apr-2021

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements