Target Sum solution explained

Target Sum counts the ways to put a plus or minus sign in front of every number in a list so the signed total equals a target. If P is the sum of the numbers that get a plus and the total of all numbers is T, then P = (T + target) / 2, so the question becomes how many subsets add up to that value. A counting version of the 0/1 knapsack table answers it in O(n · P) time, after checking that T + target is even and that the target lies between -T and T.

By Published 8 min read

The problem, restated

You have a row of number cards and a target. In front of every card you must write either a plus or a minus, then add everything up. How many of the possible sign patterns give exactly the target? Every card gets a sign; none can be left out. Two patterns differ if any card has a different sign, even when the cards share a value.

Examples written for this page
NumbersTargetWaysWhich patterns
[2, 1, 1]22+2 +1 -1 and +2 -1 +1
[1, 2, 3]02+1 +2 -3 and -1 -2 +3
[4]-41-4
[3, 5]10Total 8 plus target 1 is odd, so no pattern works
[0, 0, 1]14Each zero can be + or -, so 2 x 2 patterns
Examples written for this page. Scroll sideways on a small screen.

What the interviewer is checking

The direct memoized recursion is acceptable, and many interviewers will take it. What earns extra credit is the short piece of algebra that turns signs into a subset count, and then getting the details of that count right: the parity check, the range check and zeros. It also shows whether you can recognize a knapsack problem when it does not mention weights or capacity.

Follow-ups

  • List the patterns, not just count them. Backtracking is needed, and the output itself can have 2^n entries.
  • Negative numbers in the input. The subset reduction relies on non-negative values; with negatives, use the running-sum map, which handles any integers.
  • Smaller table. Count subsets for the minus group instead, (T - target) / 2, whichever is smaller.
  • Is any pattern possible at all? Same table with booleans instead of counts, which is the partition-style yes-or-no question.

Brute force

Each number takes one of two signs, so there are 2^n patterns. Recursing through the list and trying both signs at each step visits all of them. It is fine for about twenty numbers and hopeless beyond that. The waste is that many different prefixes of signs reach the same running total, and from there the rest of the work is identical.

def count_sign_ways_slow(nums, target, i=0, running=0):
    if i == len(nums):
        return 1 if running == target else 0
    plus = count_sign_ways_slow(nums, target, i + 1, running + nums[i])
    minus = count_sign_ways_slow(nums, target, i + 1, running - nums[i])
    return plus + minus
Python: try both signs for every number. O(2^n).

A direct fix: count running sums

Since only the running total matters, keep a map from each reachable running total to the number of sign patterns that reach it. Each new number moves every entry both up and down by its value. After the last number, read the count stored at the target. The map holds at most 2T + 1 keys, so this is O(n · T) and handles negative inputs too.

from collections import Counter

def count_sign_ways_map(nums, target):
    totals = Counter({0: 1})  # running total -> number of patterns
    for x in nums:
        nxt = Counter()
        for running, count in totals.items():
            nxt[running + x] += count
            nxt[running - x] += count
        totals = nxt
    return totals[target]
Python: a Counter of running totals.

The optimal approach: count subsets

Split the numbers into the plus group, with sum P, and the minus group, with sum M. Then P - M equals the target and P + M equals the total T. Adding the two equations gives 2P = T + target. So every valid pattern corresponds to exactly one subset with sum (T + target) / 2, and the answer is the number of such subsets. If T + target is odd, or the target is outside the range -T to T, the answer is zero right away.

Counting subsets with a given sum is the counting form of the 0/1 knapsack. ways[s] holds how many subsets of the numbers seen so far sum to s. Each number adds ways[s - x] into ways[s], with s running from high to low so the number is used at most once. The loop must go all the way down to s = x. For a zero that means s = 0 is included, and ways[0] doubles, which is correct: a zero can be in the plus group or the minus group without changing anything.

def count_sign_ways(nums, target):
    total = sum(nums)
    if abs(target) > total or (total + target) % 2:
        return 0
    goal = (total + target) // 2  # sum of the numbers that get a plus
    ways = [0] * (goal + 1)
    ways[0] = 1
    for x in nums:
        for s in range(goal, x - 1, -1):  # downward, and down to s = x
            ways[s] += ways[s - x]
    return ways[goal]
Python: reduction to a subset count. O(n · P) time, O(P) memory.
function findTargetSumWays(nums, target) {
  let total = 0;
  for (const x of nums) total += x;
  if (Math.abs(target) > total || (total + target) % 2 !== 0) return 0;
  const goal = (total + target) / 2;
  const ways = new Array(goal + 1).fill(0);
  ways[0] = 1;
  for (const x of nums) {
    for (let s = goal; s >= x; s--) {
      ways[s] += ways[s - x];
    }
  }
  return ways[goal];
}
JavaScript: the same reduction.

Trace [2, 1, 1] with target 2. The total is 4, so the plus group must sum to 3. Start with ways = [1, 0, 0, 0]. After 2: [1, 0, 1, 0]. After the first 1: [1, 1, 1, 1]. After the second 1: [1, 2, 2, 2]. ways[3] = 2, matching the two patterns in the table: the 2 with either one of the 1s gets a plus.

Complexity

n numbers with total T; P = (T + target) / 2
ApproachTimeExtra memory
Try every sign patternO(2^n)O(n) stack
Memoized recursion on (index, running total)O(n · T)O(n · T)
Map of running totalsO(n · T)O(T)
Subset count, 1D arrayO(n · P)O(P)
n numbers with total T; P = (T + target) / 2. Scroll sideways on a small screen.

Edge cases

  • Target larger than the total, or smaller than its negative: 0.
  • Total plus target odd: 0.
  • Zeros in the list: each one doubles the count.
  • A negative target: the formula still works, since the plus group then sums to less than half.
  • An empty list: one pattern (no signs at all) if the target is 0, otherwise none.

Common mistakes

  • Skipping the parity check, so integer division silently produces a wrong goal.
  • Skipping the range check, which can give a negative goal and a crash on array creation.
  • Stopping the inner loop at s > x or s >= 1, which loses the doubling for zeros.
  • Running the inner loop upward, which lets a number join the plus group twice.
  • Treating it as choosing some numbers to add and ignoring the rest; every number must be signed.

How to explain it out loud

Fictional example

From signs to a subset
Candidate
The brute force tries both signs for each number, two to the n. Since only the running total matters, I could memoize on index and total and get n times the sum.
Candidate
There is a cleaner form. If the plus group sums to P and everything sums to T, then P minus the rest is the target, so P is T plus target over two. If that is not a whole number, or the target is out of range, the answer is zero.
Candidate
Then I count subsets with sum P, using one array filled from high to low. I go all the way down to the number itself so a zero doubles the counts, since a zero works with either sign.

Partition Equal Subset Sum is the yes-or-no form of the same table, with a goal of half the total. Coin Change II counts combinations too, but lets each value repeat, so its inner loop goes up instead of down. Doing the three back to back is a fast way to learn the knapsack family.

Practicing with Natively

The algebra step is short but easy to fumble while someone watches, so say it out loud a few times. In a practice session, Natively on Mac or Windows can read the problem from a screenshot and point toward the subset reduction, which is a good check after your own attempt, and the transcript of your mock shows whether you mentioned the parity and zero cases. More on the AI interview assistant.

Questions people ask

How do you solve Target Sum?

Let T be the total of the numbers. The numbers with a plus sign must sum to (T + target) / 2, so count the subsets with that sum using a 0/1 knapsack counting array filled from high sums to low. Return 0 if T + target is odd or the target is outside -T to T.

Why is Target Sum a subset sum problem?

If the plus group sums to P and the minus group to M, then P - M is the target and P + M is the total. Adding the equations gives P = (total + target) / 2, so each valid sign pattern is one subset with that sum.

How do zeros affect Target Sum?

Each zero can take either sign without changing the total, so it doubles the count. In the subset-count loop, letting s run down to the number itself (s = 0 for a zero) handles this automatically.

What is the time complexity of Target Sum?

Trying every sign pattern is O(2^n). The subset-count method is O(n · P) time and O(P) memory, where P = (total + target) / 2.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP