AlgoTales · Roadmap

Equal partition

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Equal partition asks whether a set of numbers can be split into two groups with exactly the same total. If the grand total is odd it is impossible; otherwise you look for a group adding to half. It is a fairness check that reduces to subset sum.

Practical use cases

  • Web app: Splitting jobs between two servers. A job-runner admin page has tasks with known durations and two worker machines. The team wants both to finish at exactly the same time. The code checks whether some of the tasks add up to half of the total time, and if so, assigns those to the first server. Both servers finish together, so no machine sits idle waiting for the other, and the whole nightly batch ends earlier than with a simple alternating split.
  • Web app: Fair expense split app. A group-expense app lets two friends divide a list of bills so each pays the same amount without splitting any single bill. It tells them whether this is possible and which bills each person takes. If the total of all bills is odd, the app says so instantly and suggests rounding one bill, instead of letting the friends argue over an impossible split.
  • System: Load balancing and fair division. Load balancers and inheritance-splitting tools try to share indivisible items into equal halves. If an equal split exists, the half-total check finds it. In each of these, the first check is whether the total is even, and the second is whether some group reaches exactly half, which is the subset sum table again.

The story: Two Brothers and the Mango Basket

Grandpa Bhaskar returned from the orchard with a basket of four mangoes weighing 1, 5, 11 and 5 kilos. (They were rather large mangoes!) His grandsons Kabir and Aarav both wanted the biggest share, and every argument ended in tears. "Fair is fair," said Grandpa. "Split them into two piles that weigh exactly the same. If you can't, I'll eat them myself."

Kabir weighed one pile, then another, then added a mango, then removed it... a mess. Mira stopped them. "First add up all the mangoes: 22 kilos. If the total were odd, like 21, two equal piles would be impossible. 22 is even, so each brother needs 11 kilos. Now here is the trick: if I can find a group of mangoes that weighs exactly 11, whatever is left must also weigh exactly 11!"

That turned the puzzle into the one from the toll gate: subset sum, with a target of half the total. She kept a list of every weight she could make with the mangoes so far. When the last mango was added, 11 was in the list. One brother got the 11 kg mango, and the other got 1, 5 and 5. Grandpa was proud and kept his appetite for dinner.

This puzzle is called equal partition (or partition equal subset sum): can a set of numbers be split into two groups with equal sums? Two steps: check the total is even, then ask whether half of it is a reachable subset sum.

How to spot this problem, and where you need it

You have indivisible items with numbers attached and need to split them into two groups with exactly the same total, or find that it cannot be done.

Signs you need it

  • The problem says "two groups with equal sum", "split evenly" or "fair division" and items cannot be cut.
  • Adding all items gives an odd number, which immediately tells you the answer is no.
  • You need to assign each task or bill to side A or side B, and trying all assignments is too slow.

Where to use it in a project

  • Balancing task time between two workers, servers or queues.
  • Group expense and fair-share features dealing with whole bills or items.

The solution

Add up all the numbers. If the total is odd, answer no. Otherwise the target is half the total. Now ask whether any subset adds to the target, using the subset-sum table: mark total 0 as reachable, then for each number mark every total reachable by adding it to an already reachable total, going from high to low. If the target is marked, an equal split exists.

Payoff: Before: trying every possible split, over a million for 20 bills. After: a small table of about 20 rows, with an instant yes or no.

Explain it like I am 8

Two kids share a pile of toys by weight. First weigh everything. If the total can't be cut into two equal halves (an odd number), stop: it is impossible. Otherwise, figure out whether you can pick some toys that weigh exactly half. If you can, the rest automatically weigh the other half.

How it works, step by step

  1. Add everything up. If the total is odd, the answer is "no", because two equal halves can't make an odd number.
  2. Set the target to half the total. Now we only need one pile with exactly that sum.
  3. Run subset sum: dp[0] = true; for each number x, for sums from the target down to x, dp[s] = dp[s] or dp[s - x].
  4. Answer: dp[target]. If true, a group of exactly half exists, and the rest is the other half.
  5. Quick exits: a single number bigger than half the total makes the answer "no" immediately; the DP handles that automatically.

The code in four languages

PHP

<?php
// Equal partition: can the numbers be split into two groups with the same sum?
function canSplitEqually(array $nums): bool {
    $total = array_sum($nums);
    if ($total % 2 !== 0) return false;          // an odd total can never be split evenly
    $target = intdiv($total, 2);                 // we only need ONE group that weighs half
    $dp = array_fill(0, $target + 1, false);
    $dp[0] = true;                               // empty group weighs 0
    foreach ($nums as $x) {
        for ($s = $target; $s >= $x; $s--) {     // big to small: use each number once
            if ($dp[$s - $x]) $dp[$s] = true;
        }
    }
    return $dp[$target];
}

var_dump(canSplitEqually([1, 5, 11, 5]));        // bool(true)  (11 | 1 + 5 + 5)
var_dump(canSplitEqually([1, 2, 3, 5]));         // bool(false) (total 11 is odd)
var_dump(canSplitEqually([2, 2, 3, 5]));         // bool(false) (total 12, but no group makes 6)

JavaScript

// Equal partition: can the numbers be split into two groups with the same sum?
function canSplitEqually(nums) {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total % 2 !== 0) return false;             // an odd total can never be split evenly
  const target = total / 2;                      // we only need ONE group that weighs half
  const dp = new Array(target + 1).fill(false);
  dp[0] = true;                                  // empty group weighs 0
  for (const x of nums) {
    for (let s = target; s >= x; s--) {          // big to small: use each number once
      if (dp[s - x]) dp[s] = true;
    }
  }
  return dp[target];
}

console.log(canSplitEqually([1, 5, 11, 5]));     // true  (11 | 1 + 5 + 5)
console.log(canSplitEqually([1, 2, 3, 5]));      // false (total 11 is odd)
console.log(canSplitEqually([2, 2, 3, 5]));      // false (total 12, but no group makes 6)

Java

public class Main {
    // Equal partition: can the numbers be split into two groups with the same sum?
    static boolean canSplitEqually(int[] nums) {
        int total = 0;
        for (int x : nums) total += x;
        if (total % 2 != 0) return false;            // an odd total can never be split evenly
        int target = total / 2;                      // we only need ONE group that weighs half
        boolean[] dp = new boolean[target + 1];
        dp[0] = true;                                // empty group weighs 0
        for (int x : nums) {
            for (int s = target; s >= x; s--) {      // big to small: use each number once
                if (dp[s - x]) dp[s] = true;
            }
        }
        return dp[target];
    }

    public static void main(String[] args) {
        System.out.println(canSplitEqually(new int[]{1, 5, 11, 5}));     // true  (11 | 1 + 5 + 5)
        System.out.println(canSplitEqually(new int[]{1, 2, 3, 5}));      // false (total 11 is odd)
        System.out.println(canSplitEqually(new int[]{2, 2, 3, 5}));      // false (total 12, but no group makes 6)
    }
}

Go

package main

import "fmt"

// Equal partition: can the numbers be split into two groups with the same sum?
func canSplitEqually(nums []int) bool {
	total := 0
	for _, x := range nums {
		total += x
	}
	if total%2 != 0 {
		return false // an odd total can never be split evenly
	}
	target := total / 2 // we only need ONE group that weighs half
	dp := make([]bool, target+1)
	dp[0] = true // empty group weighs 0
	for _, x := range nums {
		for s := target; s >= x; s-- { // big to small: use each number once
			if dp[s-x] {
				dp[s] = true
			}
		}
	}
	return dp[target]
}

func main() {
	fmt.Println(canSplitEqually([]int{1, 5, 11, 5})) // true  (11 | 1 + 5 + 5)
	fmt.Println(canSplitEqually([]int{1, 2, 3, 5}))  // false (total 11 is odd)
	fmt.Println(canSplitEqually([]int{2, 2, 3, 5}))  // false (total 12, but no group makes 6)
}

Time: O(n × total/2) · Extra space: O(total/2). It is subset sum with half the total as the target: one flag per possible weight, updated once per number.

Watch out for

  • Skipping the odd-total check and just running the table. It works, but you waste time (and with an odd total, total / 2 in JS becomes a decimal).
  • Looping the sums upward in the 1-row version, which would reuse a number and give false "yes" answers.
  • Searching for both groups. Only one group needs to be found, the other is the leftover.

Quick check

  1. The numbers add up to 15. Can they be split into two equal-sum groups?
    • Yes, always
    • No, an odd total cannot be halved into whole numbers
    • Only if sorted
  2. Which problem does equal partition reduce to?
    • Shortest path
    • Subset sum with target = half of the total
    • Sorting
  3. For [2, 2, 3, 5] (total 12), why is the answer false?
    • The total is odd
    • There are too few numbers
    • No group of numbers adds up to 6