Subarray pairs with equal sums in JavaScript

We are required to write a JavaScript function that takes in an array of integers as the only argument.

The function should determine whether there exists any way in which we can split the array into two subarrays such that the sum of the elements present in the two subarrays are equal. While dividing the elements into subarrays we have to make sure that no element from the original array is left.

Problem Understanding

For example, if the input array is:

const arr = [5, 3, 7, 4, 1, 8, 2, 6];

Then the output should be true because the desired subarrays are: [5, 3, 4, 6] and [7, 1, 8, 2] with both having sum equal to 18.

Algorithm Approach

The solution uses dynamic programming. First, we calculate the total sum. If it's odd, we can't split into equal parts. If even, we need to find if there's a subset with sum equal to half of the total sum.

Example

const arr = [5, 3, 7, 4, 1, 8, 2, 6];

const canPartition = (arr = []) => {
    const sum = arr.reduce((acc, val) => acc + val);
    if (sum % 2 !== 0) {
        return false;
    }
    
    const target = sum / 2;
    const dp = new Array(target + 1).fill(false);
    dp[0] = true;
    
    for (const num of arr) {
        if (dp[target - num]) {
            return true;
        }
        for (let i = target; i >= num; i--) {
            dp[i] = dp[i - num];
        }
    }
    return false;
};

console.log(canPartition(arr));
console.log("Array sum:", arr.reduce((a, b) => a + b));
console.log("Target sum for each partition:", arr.reduce((a, b) => a + b) / 2);
true
Array sum: 36
Target sum for each partition: 18

How It Works

The algorithm creates a boolean array dp where dp[i] represents whether we can achieve sum i using array elements. We iterate through each number and update the dp array backwards to avoid using the same element twice.

Edge Cases

// Test with odd sum (impossible to partition)
console.log(canPartition([1, 2, 4])); // false, sum = 7

// Test with single element
console.log(canPartition([5])); // false, can't split one element

// Test with even elements but no valid partition
console.log(canPartition([1, 1, 1, 1, 1, 1, 1, 15])); // false
false
false
false

Time and Space Complexity

Complexity Value Explanation
Time O(n × sum) Iterate through array for each possible sum
Space O(sum) DP array of size target + 1

Conclusion

This dynamic programming solution efficiently determines if an array can be partitioned into two equal-sum subarrays. The key insight is converting the problem into finding a subset with sum equal to half the total sum.

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

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements