AlgoTales · Roadmap

Target sum

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

Where you will meet this in real life

Target sum counts the ways to put a plus or minus sign before each number so the total equals a target. With a small trick it turns into counting subsets that add to one special number. It shows how a problem that looks new can reduce to one you already know.

Practical use cases

  • Web app: Balancing credits and debits. An accounting screen has a list of entries that can be booked as credit or debit, and the auditor wants to know how many ways give a net balance of exactly 500. Instead of trying every plus-minus assignment, the code counts subsets that add to a single derived number. The answer appears at once, even for 40 entries.
  • Web app: Scoring puzzle game. A puzzle app shows numbers and asks the player to choose plus or minus for each to reach a goal. The backend counts how many solutions exist, so the app can rate difficulty and avoid puzzles with only one answer. Puzzles with a single solution feel too easy and puzzles with thousands feel pointless, so the count helps the team pick a comfortable middle for players.
  • System: Budget splitting and fair division. Planning software splits items into an "add" group and a "subtract" group to hit a net figure. Counting the splits uses the same reduction. In each of these, a plus-minus puzzle quietly becomes a counting puzzle on one special number, which is the same table that other knapsack-style problems use.

The story: The Plus-Minus Chits

At the school fair, Raju's chai stall ran a game. Four chits lay on the counter: 1, 1, 2 and 3. "Write a + or a − in front of every chit," said Raju. "If the total comes to exactly 1, you win a free chai!" Mira tried a few combinations, but there were so many that she lost track.

Kabir spotted a shortcut. "Every chit is either on the plus pile or the minus pile. The total of all chits is 7. If the plus pile adds up to 4, the minus pile adds up to 3, and 4 − 3 is exactly 1!" So the puzzle changed shape: how many ways can some of the chits add up to 4?

Now it was a friend of an old puzzle: choose-or-skip for each chit and count the ways, remembering the count for every possible total on a small strip of paper. Each new chit adds to the strip: "ways to make 4 = old ways to make 4 + old ways to make 4 − chit." Three ways won the chai. This is Target Sum: a counting version of subset sum.

How to spot this problem, and where you need it

You need to count the ways to give each number a plus or minus sign so the result equals a target, and trying all sign combinations takes too long.

Signs you need it

  • The problem says "assign + or - to each number" and asks for how many ways to reach a target.
  • There are many numbers, so the number of sign combinations doubles with each extra number and is far too many to try.
  • You suspect it is the same as splitting the numbers into two piles with a given difference.

Where to use it in a project

  • Counting ways to reach a net amount in accounting or ledger tools.
  • Rating difficulty of puzzle or scoring games by counting solutions.

The solution

Let the "plus" group have sum P and the "minus" group sum M. Then P plus M equals the total and P minus M equals the target, so P equals (total plus target) divided by 2. If that is not a whole number or is negative, answer zero. Otherwise count how many subsets of the numbers add up to P, using a table of ways for each sum from 0 to P, updated for each number from high to low.

Payoff: Before: over a million sign patterns for 20 numbers. After: one table of a few hundred entries.

Explain it like I am 8

Every chit goes to either the "plus" team or the "minus" team. Instead of trying every team, you notice the plus team just has to add up to one special number. Then you count the ways to build that number, writing the counts on a paper strip.

How it works, step by step

  1. Add up everything (total). If the target is bigger than the total, or the total plus target is odd, the answer is 0.
  2. Find the plus-pile size: (total + target) divided by 2. Call it need.
  3. Make a strip ways[0..need]. ways[0] = 1 (pick nothing), the rest 0.
  4. For each number, walk the strip from right to left: ways[s] += ways[s - x]. Going backwards means a chit is used at most once.
  5. The answer is ways[need].

The code in four languages

PHP

<?php
// Count ways to put + or - before each number so the result equals $target.
function targetSum(array $nums, int $target): int {
    $total = array_sum($nums);
    // impossible if target is out of reach or the plus pile would be fractional
    if (abs($target) > $total || ($total + $target) % 2 !== 0) return 0;
    $need = intdiv($total + $target, 2);      // the plus pile must add up to this
    $ways = array_fill(0, $need + 1, 0);
    $ways[0] = 1;                             // one way to make 0: choose nothing
    foreach ($nums as $x) {
        for ($s = $need; $s >= $x; $s--) {    // right to left: each number used once
            $ways[$s] += $ways[$s - $x];
        }
    }
    return $ways[$need];
}
echo targetSum([1, 1, 2, 3], 1), "\n";        // 3
echo targetSum([1, 1, 1, 1, 1], 3), "\n";     // 5

JavaScript

// Count ways to put + or - before each number so the result equals target.
function targetSum(nums, target) {
  const total = nums.reduce((a, b) => a + b, 0);
  // impossible if target is out of reach or the plus pile would be fractional
  if (Math.abs(target) > total || (total + target) % 2 !== 0) return 0;
  const need = (total + target) / 2;          // the plus pile must add up to this
  const ways = new Array(need + 1).fill(0);
  ways[0] = 1;                                // one way to make 0: choose nothing
  for (const x of nums) {
    for (let s = need; s >= x; s--) {         // right to left: each number used once
      ways[s] += ways[s - x];
    }
  }
  return ways[need];
}
console.log(targetSum([1, 1, 2, 3], 1));      // 3
console.log(targetSum([1, 1, 1, 1, 1], 3));   // 5

Java

public class Main {
    // Count ways to put + or - before each number so the result equals target.
    static int targetSum(int[] nums, int target) {
        int total = 0;
        for (int x : nums) total += x;
        // impossible if target is out of reach or the plus pile would be fractional
        if (Math.abs(target) > total || (total + target) % 2 != 0) return 0;
        int need = (total + target) / 2;          // the plus pile must add up to this
        int[] ways = new int[need + 1];
        ways[0] = 1;                              // one way to make 0: choose nothing
        for (int x : nums) {
            for (int s = need; s >= x; s--) {     // right to left: each number used once
                ways[s] += ways[s - x];
            }
        }
        return ways[need];
    }

    public static void main(String[] args) {
        System.out.println(targetSum(new int[]{1, 1, 2, 3}, 1));      // 3
        System.out.println(targetSum(new int[]{1, 1, 1, 1, 1}, 3));   // 5
    }
}

Go

package main

import "fmt"

// Count ways to put + or - before each number so the result equals target.
func targetSum(nums []int, target int) int {
	total := 0
	for _, x := range nums {
		total += x
	}
	// impossible if target is out of reach or the plus pile would be fractional
	if abs(target) > total || (total+target)%2 != 0 {
		return 0
	}
	need := (total + target) / 2 // the plus pile must add up to this
	ways := make([]int, need+1)
	ways[0] = 1 // one way to make 0: choose nothing
	for _, x := range nums {
		for s := need; s >= x; s-- { // right to left: each number used once
			ways[s] += ways[s-x]
		}
	}
	return ways[need]
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	fmt.Println(targetSum([]int{1, 1, 2, 3}, 1))    // 3
	fmt.Println(targetSum([]int{1, 1, 1, 1, 1}, 3)) // 5
}

Time: O(n × need) · Extra space: O(need). One pass of the strip per number; without the plus-pile trick you would try all 2ⁿ sign choices.

Watch out for

  • Walking the strip left to right: a chit then gets used several times (that is the unbounded version).
  • Forgetting the early exit: when the total plus target is odd or the target is too big, the answer is 0 and need would be nonsense.
  • Starting with ways[0] = 0. With zero chits there is exactly one way to make 0, so it must be 1.

Quick check

  1. Chits 1,1,2,3 and target 1. What must the plus pile add up to?
    • 3
    • 4
    • 7
  2. Why do we walk the strip from right to left?
    • It is faster
    • So each chit is used at most once
    • To sort the numbers
  3. Total is 6 and target is 3. How many ways?
    • At least one
    • Exactly 3
    • Zero, because 6 + 3 is odd