Coding Challenge: Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.

Please follow & like us :)

JavaScript interview questions and answers
Input: [1, 2, 4, 6, 7, 5], 12
Output: [7,5]

Logic Implementation: We can keep adding numbers from array. We can check conditions, if it is equal to given sum we can slice array and return it. If it is less than given sum we can keep adding numbers. If it is more than given sum we can subtract first number and update the index value from 0 to 1.

Checkout Coding Challenge Tutorial

Here is the working solution!

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, 2, 4, 6, 7, 5], 12));