Removing smallest subarray to make array sum divisible in JavaScript


We are required to write a JavaScript function that takes in an array of positive integers as the first argument and a positive integer as the second argument.

The function should figure out and return the length of the smallest subarray that we should delete from the original array in order to make its sum divisible by the number specified by the second argument.

For example −

If the input is −

const arr = [3, 8, 2, 6];
const num = 9;

Then the output should be −

const output = 2

Because the subarray that needs to be deleted is [8, 2]

Example

Following is the code −

const arr = [3, 8, 2, 6];
const num = 9;
const minimumDeletion = (arr = [], num) => {
   const diff = arr.reduce((a, b) => a + b) % num;
   let res = diff == 0 ? 0 : arr.length;
   for (let i = 0, sum = 0, map = {0: -1}; i < arr.length; i++) {
      sum += arr[i];
      const target = (sum % num - diff + num) % num;
      if (map[target] != undefined) {
         res = Math.min(res, i - map[target]);
      };
      map[sum % num] = i;
   };
   return res == arr.length ? -1 : res;
};
console.log(minimumDeletion(arr, num));

Output

Following is the console output −

2

Updated on: 18-Jan-2021

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements