Browse curriculum

Target Sum (LeetCode 494)

Target Sum (LeetCode 494): count the ways to put + and − in front of each number to reach a target, by turning it into counting subsets with sum (total + target) / 2.

Problem Understanding

Target Sum: put a + or − in front of every number in nums, then add them all. Return how many sign choices give exactly target.

Example: nums = [1, 1, 1, 1, 1], target = 3 returns 5: one of the five 1s gets a minus sign.

Attempt 1: Try Every Sign

Each number has two signs, so there are 2^n combinations. A DFS over (index, running sum) is correct, and memoising it helps, but the running sum can be negative and the state space is awkward. A little algebra removes the signs entirely.

The Intuition: Signs Are Just a Subset

Split the numbers into the plus group P and the minus group N:

  • P − N = target
  • P + N = total

Adding them: P = (total + target) / 2. So a sign choice is nothing more than a subset whose sum is (total + target) / 2. If that is not a whole number, or |target| > total, the answer is 0.

Counting subsets with a given sum is the counting version of Partition Equal Subset Sum: dp[j] is the number of subsets that add up to j, dp[0] = 1, and for each number dp[j] += dp[j − num] for j going down, so each number is used once.

Target Sum Visualization

TARGET 3 · PLUS GROUP MUST SUM TO 4

P = (TOTAL + TARGET) / 2

nums

1
1
1
1
1

dp: subsets adding up to j

1

0

0

1

0

2

0

3

0

4

num

:

j

:

Answer

:

 

Plus group P − minus group N = 3, P + N = 5, so the plus group must add up to (5 + 3) / 2 = 4. Count subsets with that sum; dp[0] = 1

Next

Number 1: sweep j from 4 down to 1, so it joins each subset at most once

Free preview: the first 9 of 27 steps

nums

Target

The numbers are on top, with the one being added marked. Below, dp[j] counts the subsets that make j, up to the plus group's sum. The sweep runs right to left: j reads dp[j − num], which is shaded.

Target Sum Dry Run

Input: nums = [1, 1, 1, 1, 1], target = 3. total = 5, so the plus group sums to (5 + 3) / 2 = 4.

After number dp[0] dp[1] dp[2] dp[3] dp[4]
(start) 1 0 0 0 0
1st 1 1 1 0 0 0
2nd 1 1 2 1 0 0
3rd 1 1 3 3 1 0
4th 1 1 4 6 4 1
5th 1 1 5 10 10 5

Five ways: choose which four 1s are positive.

Target Sum LeetCode Solution

Reduce to counting subsets with sum (total + target) / 2, then a 1D 0/1 knapsack.

Target Sum Code
1var findTargetSumWays = function(nums, target) {
2 const total = nums.reduce((a, b) => a + b, 0);
3 if (Math.abs(target) > total || (total + target) % 2) return 0;
4 const goal = (total + target) / 2;
5 const dp = new Array(goal + 1).fill(0);
6 dp[0] = 1;
7 for (const num of nums) {
8 for (let j = goal; j >= num; j--) {
9 dp[j] += dp[j - num];
10 }
11 }
12 return dp[goal];
13};

Target Sum in Python, Java, C++, TypeScript and C

Target Sum in Python
class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        total = sum(nums)
        if abs(target) > total or (total + target) % 2:
            return 0
        goal = (total + target) // 2
        dp = [0] * (goal + 1)
        dp[0] = 1
        for num in nums:
            for j in range(goal, num - 1, -1):
                dp[j] += dp[j - num]
        return dp[goal]
Target Sum in Java
class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        int total = 0;
        for (int num : nums) total += num;
        if (Math.abs(target) > total || (total + target) % 2 != 0) return 0;
        int goal = (total + target) / 2;
        int[] dp = new int[goal + 1];
        dp[0] = 1;
        for (int num : nums) {
            for (int j = goal; j >= num; j--) {
                dp[j] += dp[j - num];
            }
        }
        return dp[goal];
    }
}
Target Sum in C++
class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int total = accumulate(nums.begin(), nums.end(), 0);
        if (abs(target) > total || (total + target) % 2) return 0;
        int goal = (total + target) / 2;
        vector<int> dp(goal + 1, 0);
        dp[0] = 1;
        for (int num : nums) {
            for (int j = goal; j >= num; j--) {
                dp[j] += dp[j - num];
            }
        }
        return dp[goal];
    }
};
Target Sum in TypeScript
function findTargetSumWays(nums: number[], target: number): number {
    const total = nums.reduce((a, b) => a + b, 0);
    if (Math.abs(target) > total || (total + target) % 2) return 0;
    const goal = (total + target) / 2;
    const dp: number[] = new Array(goal + 1).fill(0);
    dp[0] = 1;
    for (const num of nums) {
        for (let j = goal; j >= num; j--) {
            dp[j] += dp[j - num];
        }
    }
    return dp[goal];
}
Target Sum in C
int findTargetSumWays(int* nums, int numsSize, int target) {
    int total = 0;
    for (int i = 0; i < numsSize; i++) total += nums[i];
    if (abs(target) > total || (total + target) % 2) return 0;
    int goal = (total + target) / 2;
    int* dp = calloc(goal + 1, sizeof(int));
    dp[0] = 1;
    for (int i = 0; i < numsSize; i++) {
        for (int j = goal; j >= nums[i]; j--) {
            dp[j] += dp[j - nums[i]];
        }
    }
    int ans = dp[goal];
    free(dp);
    return ans;
}

Edge Cases & Common Mistakes

  • |target| > total: return 0 before computing a negative or oversized goal.
  • Odd total + target: no subset can sum to a half; return 0.
  • Negative target: the formula still works, as long as |target| ≤ total.
  • Zeros: each 0 doubles the count; make sure the inner loop includes j = num = 0.
  • Sweeping upward: that reuses a number within one pass and overcounts.

Summary

A sign choice is a subset P with P − N = target and P + N = total, so P sums to (total + target) / 2. Rule out impossible targets, then count subsets with that sum using dp[j] += dp[j − num] with j descending. O(n · sum) time, O(sum) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Rule out impossible targets

    If |target| > total or (total + target) is odd, return 0.

  2. Turn it into subset sum

    Let goal = (total + target) / 2 and count subsets that add up to goal, with dp[0] = 1.

  3. Count with a 0/1 knapsack

    For each num, for j from goal down to num, dp[j] += dp[j − num]. Return dp[goal].

Frequently asked questions

Why does the plus group have to sum to (total + target) / 2?

Call the numbers given + the group P and the rest N. Then P − N = target and P + N = total. Adding the two equations gives 2P = total + target, so P = (total + target) / 2. Every valid sign choice is exactly one subset with that sum.


When is the answer 0 immediately?

When |target| is larger than the total, since no signs can reach it, or when total + target is odd, since P would not be a whole number.


How are zeros handled?

A 0 can take either sign without changing the sum, so it should double the count. The 0/1 knapsack does that automatically: for num = 0 the loop runs down to j = 0 and dp[j] += dp[j] doubles every entry.

New to the technique behind this problem? Watch it run step by step:

Dynamic Programming Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description