Finding n subarrays with equal sum in JavaScript

We are required to write a JavaScript function that takes in an array of integers as the first argument and an integer as the second argument.

The function should check whether we can create n (second argument) subarrays from the original array such that all the subarrays have the equal sum.

For example ?

If the inputs are ?

const arr = [4, 3, 2, 3, 5, 2, 1];
const num = 4;

The output should be true because the subarrays are: [5], [1, 4], [2, 3], [2, 3] all having sum equal to 5.

How It Works

The algorithm uses backtracking to partition the array into n equal-sum subarrays:

  1. Calculate the total sum and check if it's divisible by n
  2. Find the target sum for each subarray (total / n)
  3. Use backtracking to try all possible combinations
  4. Mark elements as visited to avoid reuse

Example

Following is the code ?

const arr = [4, 3, 2, 3, 5, 2, 1];
const num = 4;

const canFormSubarray = (arr = [], num) => {
    const total = arr.reduce((sum, num) => sum + num, 0);

    if (total % num !== 0) {
        return false;
    }
    
    const target = total / num;
    const visited = new Array(arr.length).fill(false);
    
    const canPartition = (start, numberOfSubsets, currentSum) => {
        if (numberOfSubsets === 1) {
            return true;
        }
        if (currentSum === target) {
            return canPartition(0, numberOfSubsets - 1, 0);
        }
        
        for (let i = start; i < arr.length; i++) {
            if (!visited[i]) {
                visited[i] = true;
                if (canPartition(i + 1, numberOfSubsets, currentSum + arr[i])) {
                    return true;
                }
                visited[i] = false;
            }
        }
        return false;
    };
    
    return canPartition(0, num, 0);
};

console.log(canFormSubarray(arr, num));

Output

Following is the console output ?

true

Step-by-Step Breakdown

Let's trace through the example:

const arr = [4, 3, 2, 3, 5, 2, 1];
const num = 4;

// Step 1: Calculate total sum
const total = arr.reduce((sum, num) => sum + num, 0);
console.log("Total sum:", total); // 20

// Step 2: Check if divisible by n
console.log("20 % 4 === 0:", total % num === 0); // true

// Step 3: Calculate target sum for each subarray
const target = total / num;
console.log("Target sum per subarray:", target); // 5
Total sum: 20
20 % 4 === 0: true
Target sum per subarray: 5

Edge Cases

The function handles several edge cases:

// Case 1: Sum not divisible by n
console.log(canFormSubarray([1, 2, 3], 2)); // false (sum=6, 6%2=0 but can't form equal subarrays)

// Case 2: Single element array
console.log(canFormSubarray([10], 1)); // true

// Case 3: Impossible partition
console.log(canFormSubarray([1, 1, 1, 1], 2)); // true (two subarrays of sum 2 each)
false
true
true

Key Points

  • Time Complexity: O(n × 2^n) in worst case due to backtracking
  • Space Complexity: O(n) for the visited array and recursion stack
  • The algorithm ensures no element is used twice using the visited array
  • Early termination when sum is not divisible by n improves efficiency

Conclusion

This backtracking solution efficiently determines if an array can be partitioned into n equal-sum subarrays. The algorithm validates feasibility first, then uses recursive exploration to find valid partitions.

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

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements