All combinations of sums for array in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n as the second argument. The number n will always be less than or equal to the length of the array.

Our function should return an array of the sum of all elements of all the possible subarrays of length n from the original array.

For example, If the input is:

const arr = [2, 6, 4];
const n = 2;

Then the output should be:

const output = [8, 10, 6];

Understanding the Problem

We need to find all possible combinations of n elements from the array and calculate their sums. For the array [2, 6, 4] with n = 2, the combinations are:

  • [2, 6] ? sum = 8
  • [2, 4] ? sum = 6
  • [6, 4] ? sum = 10

Solution Using Bit Manipulation

The following solution uses bit manipulation to generate all possible combinations:

const arr = [2, 6, 4];
const n = 2;

const buildCombinations = (arr, num) => {
    const res = [];
    let temp, i, j, max = 1 << arr.length;
    
    for(i = 0; i < max; i++){
        temp = [];
        for(j = 0; j < arr.length; j++){
            if (i & 1 << j){
                temp.push(arr[j]);
            }
        }
        if(temp.length === num){
            res.push(temp.reduce((a, b) => a + b));
        }
    }
    return res;
}

console.log(buildCombinations(arr, n));
[ 8, 6, 10 ]

How It Works

The algorithm uses bit manipulation where each bit represents whether an element is included in the current combination:

  • 1 generates 2^n possible combinations
  • i & 1 checks if the j-th bit is set in i
  • Only combinations with exactly num elements are included
  • reduce() calculates the sum of each valid combination

Alternative Recursive Solution

Here's a more intuitive recursive approach:

const arr2 = [1, 2, 3, 4];
const n2 = 3;

const getCombinationSums = (arr, n, start = 0, current = []) => {
    if (current.length === n) {
        return [current.reduce((sum, val) => sum + val, 0)];
    }
    
    let results = [];
    for (let i = start; i < arr.length; i++) {
        results = results.concat(
            getCombinationSums(arr, n, i + 1, [...current, arr[i]])
        );
    }
    return results;
}

console.log(getCombinationSums(arr2, n2));
[ 6, 7, 8, 9, 7, 8, 9, 8, 9, 10 ]

Comparison

Method Time Complexity Readability Memory Usage
Bit Manipulation O(2^n) Complex Lower
Recursive O(C(n,k)) High Higher

Conclusion

Both approaches solve the combination sum problem effectively. The bit manipulation method is more memory-efficient, while the recursive solution is more intuitive and easier to understand for beginners.

Updated on: 2026-03-15T23:19:00+05:30

917 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements