Subarray sum with at least two elements in JavaScript



Problem

We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and a single Integer, target as the second and first argument. Our function should check whether there exists a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n can be any integer.

We return true if it exists, false otherwise.

For example, if the input to the function is −

const arr = [23, 2, 6, 4, 7];
const target = 6;

Then the output should be −

const output = true;

Output Explanation:

Because [23, 2, 6, 4, 7] is a continuous subarray of size 5 and sums up to 42.

Example

The code for this will be −

 Live Demo

const arr = [23, 2, 6, 4, 7];
const target = 6;
const checkSubarraySum = (arr = [], target = 1) => {
   let sum = 0
   const hash = {}
   hash[0] = -1;
   for (let i = 0; i<arr.length; i++) {
      sum += arr[i]
      if (target!=0) sum %= target
      if ( hash[sum] !== undefined ) {
         if(i-hash[sum]>1) return true
      } else {
         hash[sum] = i
      }
   };
   return false;
};
console.log(checkSubarraySum(arr, target));

Output

And the output in the console will be −

true

Advertisements