Skip to content

Target Sum

Count the ways to put + or - in front of every number so that the total equals a target.

Medium2D Dynamic Programming
Solve on LeetCode

The problem

You get an array nums of non-negative integers and an integer target. Put a plus or a minus sign in front of every number and add them all up. Return how many sign choices give exactly target.

Input nums = [2, 1, 1], target = 2

Output 2

+2 + 1 - 1 and +2 - 1 + 1.

Input nums = [1, 0], target = 1

Output 2

+1 + 0 and +1 - 0 are different choices, so a 0 doubles the count.

Key constraint: The numbers add up to at most 1,000, so every running sum lies between -1,000 and 1,000.

How to spot the pattern

  • Every item gets one of two choices, and you count the choices that hit a total.
  • The running sums stay in a small range, so you can count ways per sum.

The idea

State: ways[i][s] is the number of sign choices for the first i numbers that add up to s. The i-th number x was either added or subtracted, so ways[i][s] = ways[i - 1][s - x] + ways[i - 1][s + x], starting from ways[0][0] = 1. Sums run from -total to total, so shift every sum by total to use it as an array index, and keep only one row at a time.

Brute force: Try all 2^n sign choices, which takes O(2^n) time.

Step by step

  1. 1Add up the numbers into total, and return 0 if abs(target) > total.
  2. 2Make ways of size 2 * total + 1 with ways[total] = 1, which stands for the sum 0.
  3. 3For each number x, build a fresh row in which every sum s with ways[s] > 0 adds its count to s + x and to s - x.
  4. 4Replace ways with the new row.
  5. 5Return ways[target + total].

See the pattern move

The 2d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        total = sum(nums)
        if abs(target) > total:
            return 0
        # ways[i][s] = ways to reach sum s with the first i numbers
        #            = ways[i - 1][s - x] + ways[i - 1][s + x] for x = nums[i - 1]
        # Sums run from -total to total, so sum s lives at index s + total; keep one row.
        ways = [0] * (2 * total + 1)
        ways[total] = 1  # before any number, the sum is 0
        for x in nums:
            nxt = [0] * (2 * total + 1)
            for s in range(2 * total + 1):
                if ways[s]:
                    nxt[s + x] += ways[s]  # put + in front of x
                    nxt[s - x] += ways[s]  # put - in front of x
            ways = nxt
        return ways[target + total]

Complexity

Time

O(n * total)

Space

O(total)

Each of the n numbers sweeps the 2 * total + 1 sums once.

Watch out for

  • Forgetting that 0 can take either sign, so each 0 doubles the count.
  • Indexing with a negative sum: shift every sum by total first.
  • Skipping the abs(target) > total check, which reads outside the array.

Follow-up questions

Is there a shorter route?

If P is the sum of the numbers with a plus sign, then P - (total - P) = target, so P = (total + target) / 2. Check that this is a whole non-negative number, then count the subsets that add up to P with a 0/1 knapsack table.

Why an array and not a hash map?

A map from sum to count works the same way and only stores sums you can reach. The array is simpler and faster when the range of sums is this small.

In Hinglish

Har number ke paas do raaste hain: + ya -. Har sum tak pahunchne ke ways ginte jao, aur negative sum ke index ke liye usmein `total` jod do.

Related problems