AlgoTales · Roadmap

Subset sum

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

Where you will meet this in real life

Subset sum asks whether some of the numbers in a list add up to exactly a target. You track which totals are possible so far and add each new number to them. It is the exact-match cousin of the knapsack problem.

Practical use cases

  • Web app: Matching a bank deposit to invoices. An accounting tool receives one bank deposit of 48,350 rupees and has 40 unpaid invoices. Finance wants to know which invoices were paid by it. The tool tracks which totals are reachable as it goes through invoices, and tells the user whether and which invoices add up to the deposit.
  • Web app: Exact payment with vouchers. A checkout page lets a customer use vouchers of fixed values and asks whether the order total can be paid exactly with them. The check runs while the customer types, because it only tracks possible totals up to the order amount. If no combination fits, the page says so right away and suggests topping up with another voucher, instead of letting the payment fail at the last step.
  • System: Reconciliation and packing. Audit software finds a set of transactions summing to a mystery amount. Packing tools check whether items can fill a container exactly. In each of these, you track which totals can be reached so far, which turns a guess-and-check puzzle into a simple table that fills in one number at a time.

The story: Exact Change at the Toll Gate

At the highway toll gate, the board said: "Pay exactly ₹9. No change given!" Aarav checked his pocket. He had six coins: 3, 34, 4, 12, 5 and 2. Could some of them add up to exactly 9? Each coin could be used once.

He tried randomly: 3 + 4 = 7, too small; 3 + 5 = 8, still short; 12 is too big already... The cars behind were honking. Mira, sitting next to him, took a pencil and wrote the numbers 0 to 9 across the page. "Let's keep a list of every amount we can make so far. We start with just 0, by taking nothing."

Now, for each coin, update the list: every amount you could already make stays possible, and every amount you could make, plus this coin, becomes possible too. After coin 3, you can make 0 and 3. After coin 4, you can make 0, 3, 4, 7. After 34, nothing new (too big). After 12, nothing new. After 5: 5, 8, 9... "There it is! 9!" shouted Aarav, and he paid with 4 and 5. The gate opened.

This is subset sum: given some numbers, can a chosen group of them (a subset) add up to exactly a target? Like the knapsack, each number is either taken or left. The table answers "yes/no" instead of a best value.

How to spot this problem, and where you need it

You have a list of amounts and need to know if some of them add to an exact figure, and trying every subset is too slow.

Signs you need it

  • The problem says "can we make exactly X from these numbers", each used once or not at all.
  • You are matching one total, such as a payment or a balance, to a group of smaller items.
  • Trying all subsets works for 20 numbers but hangs with 60.

Where to use it in a project

  • Reconciling bank deposits, settlements or refunds against invoices.
  • Checking whether vouchers, coins or credits can pay an exact amount.

The solution

Make a list of true/false flags for totals from 0 to the target. Mark total 0 as reachable. For each number, go through the totals from high to low: if total minus this number was reachable, mark this total reachable too. Going high to low prevents using the same number twice. At the end, check the flag for the target. To find which numbers were used, remember how each total was reached.

Payoff: Before: about a trillion subsets for 40 invoices. After: 40 passes over a list of 48,350 flags, finishing in under a second.

Explain it like I am 8

You have a few building blocks with numbers on them. You want a tower of exactly height 9. Start with "I can make height 0 (no blocks)". Each time you look at a block, every height you could make before can now also be made 'plus this block'. You keep a checklist of the possible heights, and at the end you look at the box for 9.

How it works, step by step

  1. State: dp[s] = "can I make the sum s using the coins considered so far?" (true or false).
  2. Base case: dp[0] = true: taking nothing makes a sum of 0.
  3. For each coin x: every s where dp[s - x] is true now makes dp[s] true (take the coin).
  4. Loop the sums from big to small inside each coin, so one coin is never used twice in the same round.
  5. The answer is dp[target]. Time is items × target, much better than trying every subset (which doubles for each extra item).

The code in four languages

PHP

<?php
// Subset sum: can some of the numbers (each used at most once) add up to the target?
function subsetSum(array $nums, int $target): bool {
    $dp = array_fill(0, $target + 1, false);
    $dp[0] = true;                               // base case: taking nothing makes 0
    foreach ($nums as $x) {
        // Go from big to small so the same coin is not used twice in one round.
        for ($s = $target; $s >= $x; $s--) {
            if ($dp[$s - $x]) $dp[$s] = true;    // take this coin on top of a possible smaller sum
        }
    }
    return $dp[$target];
}

var_dump(subsetSum([3, 34, 4, 12, 5, 2], 9));    // bool(true)  (4 + 5)
var_dump(subsetSum([3, 34, 4, 12, 5, 2], 30));   // bool(false)

JavaScript

// Subset sum: can some of the numbers (each used at most once) add up to the target?
function subsetSum(nums, target) {
  const dp = new Array(target + 1).fill(false);
  dp[0] = true;                                  // base case: taking nothing makes 0
  for (const x of nums) {
    // Go from big to small so the same coin is not used twice in one round.
    for (let s = target; s >= x; s--) {
      if (dp[s - x]) dp[s] = true;               // take this coin on top of a possible smaller sum
    }
  }
  return dp[target];
}

console.log(subsetSum([3, 34, 4, 12, 5, 2], 9));    // true  (4 + 5)
console.log(subsetSum([3, 34, 4, 12, 5, 2], 30));   // false

Java

public class Main {
    // Subset sum: can some of the numbers (each used at most once) add up to the target?
    static boolean subsetSum(int[] nums, int target) {
        boolean[] dp = new boolean[target + 1];
        dp[0] = true;                                // base case: taking nothing makes 0
        for (int x : nums) {
            // Go from big to small so the same coin is not used twice in one round.
            for (int s = target; s >= x; s--) {
                if (dp[s - x]) dp[s] = true;         // take this coin on top of a possible smaller sum
            }
        }
        return dp[target];
    }

    public static void main(String[] args) {
        System.out.println(subsetSum(new int[]{3, 34, 4, 12, 5, 2}, 9));    // true  (4 + 5)
        System.out.println(subsetSum(new int[]{3, 34, 4, 12, 5, 2}, 30));   // false
    }
}

Go

package main

import "fmt"

// Subset sum: can some of the numbers (each used at most once) add up to the target?
func subsetSum(nums []int, target int) bool {
	dp := make([]bool, target+1)
	dp[0] = true // base case: taking nothing makes 0
	for _, x := range nums {
		// Go from big to small so the same coin is not used twice in one round.
		for s := target; s >= x; s-- {
			if dp[s-x] {
				dp[s] = true // take this coin on top of a possible smaller sum
			}
		}
	}
	return dp[target]
}

func main() {
	fmt.Println(subsetSum([]int{3, 34, 4, 12, 5, 2}, 9))  // true  (4 + 5)
	fmt.Println(subsetSum([]int{3, 34, 4, 12, 5, 2}, 30)) // false
}

Time: O(n × target) · Extra space: O(target). One true/false flag per amount, updated once per coin. Trying all subsets directly would double for every coin added.

Watch out for

  • Looping the sums from small to big in the one-row version. A coin could then be reused, which changes the problem (that is the unbounded version).
  • Forgetting dp[0] = true. Without it no amount ever becomes possible.
  • Assuming sorting or greedy picking works. For exact targets, "take the biggest coin that fits" can miss the answer.

Quick check

  1. What does dp[s] = true mean?
    • The target is s
    • Some chosen group of coins considered so far adds to exactly s
    • The coin s exists
  2. Why is dp[0] true at the start?
    • Because 0 is a coin
    • Because the loop needs a start
    • Taking no coins at all makes a sum of 0
  3. Coins 2, 3. After both, which amounts can be made (0 to 6)?
    • 0, 2, 3, 5
    • 0 to 5 all
    • 0, 2, 3, 4, 5, 6