Coding Challenge – Find out the continuous sum

Please follow & like us :)

Question: Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to target k.

Here is the Sample input to understand problem and expected output.

Input: [23, 2, 4, 6, 7],  k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

To solve this problem we will scan the array and keep adding elements.

If current sum is greater than target sum, we will remove the first element and keep moving to next element until we find the target sum!

Here is the Pseudo code to use into actual code.

Pseudo Code:

for (let i = 0; i < arr.length; i++) {
  sum += arr[i];
  if (sum == Tsum) {
    return arr.slice(0, i+1);
  }
}

Here is the executable program to test continuous sum! 
Solution:

/**
 * 
 * @param {*} arr 
 * @param {*} T 
 */
const continuesSum = (arr, T) => {
    let sum = 0;
    let results = [];
    for (let i = 0, j = 0; i < arr.length; i++) {
        sum += arr[i];
        while (sum > T) {
            sum -= arr[j];
            j++;
        }
        if (sum === T) {
            results.push(arr.slice(j, i + 1));
        }
    }
    return results;
}
console.log(continuesSum([1, 3, 4, 6, 7, 5], 12));