Partition equal subset sum

Decide whether an array can be split into two groups with equal totals. A subset-sum problem in disguise.

Time O(n × sum)Space O(n × sum)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Two equal halves are only possible if the total is even, and then each half must equal total / 2. So the question becomes: can some subset of the array add up to exactly that target? dp[i, t] tracks whether sum t is reachable using the first i numbers.

Code

public static bool CanPartition(int[] a) {
    int total = a.Sum();
    if (total % 2 != 0) return false;
    int target = total / 2;
    var dp = new bool[a.Length + 1, target + 1];
    for (int i = 0; i <= a.Length; i++) dp[i, 0] = true;
    for (int i = 1; i <= a.Length; i++)
        for (int t = 1; t <= target; t++) {
            dp[i, t] = dp[i - 1, t];
            if (a[i - 1] <= t && dp[i - 1, t - a[i - 1]])
                dp[i, t] = true;
        }
    return dp[a.Length, target];
}
static boolean canPartition(int[] a) {
    int total = Arrays.stream(a).sum();
    if (total % 2 != 0) return false;
    int target = total / 2;
    boolean[][] dp = new boolean[a.length + 1][target + 1];
    for (int i = 0; i <= a.length; i++) dp[i][0] = true;
    for (int i = 1; i <= a.length; i++)
        for (int t = 1; t <= target; t++) {
            dp[i][t] = dp[i - 1][t];
            if (a[i - 1] <= t && dp[i - 1][t - a[i - 1]])
                dp[i][t] = true;
        }
    return dp[a.length][target];
}
bool canPartition(const vector<int>& a) {
    int total = accumulate(a.begin(), a.end(), 0);
    if (total % 2 != 0) return false;
    int target = total / 2, n = a.size();
    vector<vector<bool>> dp(n + 1, vector<bool>(target + 1, false));
    for (int i = 0; i <= n; i++) dp[i][0] = true;
    for (int i = 1; i <= n; i++)
        for (int t = 1; t <= target; t++) {
            dp[i][t] = dp[i - 1][t];
            if (a[i - 1] <= t && dp[i - 1][t - a[i - 1]])
                dp[i][t] = true;
        }
    return dp[n][target];
}
def can_partition(a: list[int]) -> bool:
    total = sum(a)
    if total % 2 != 0: return False
    target = total // 2
    dp = [[False] * (target + 1) for _ in range(len(a) + 1)]
    for i in range(len(a) + 1): dp[i][0] = True
    for i in range(1, len(a) + 1):
        for t in range(1, target + 1):
            dp[i][t] = dp[i - 1][t]
            if a[i - 1] <= t and dp[i - 1][t - a[i - 1]]:
                dp[i][t] = True
    return dp[len(a)][target]

Tips

In the .NET library

The odd-total check is a cheap O(n) guard that avoids building a table that can never succeed. Always check it before running the O(n × sum) table fill.