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
Updated on: 2021-03-03T07:47:25+05:30

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements