Target Sum (LeetCode 494): Solution and Explanation

Medium
Array
Dynamic Programming
Backtracking

You are given an array of non-negative integers and a target. Put either a plus or a minus sign in front of every number, then count how many sign assignments make the expression evaluate to the target.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The direct approach tries every sign choice: each number is either added or subtracted, so there are 2^n assignments, and a recursive search can evaluate them all. With up to 20 numbers that is about a million paths, which actually passes, and adding memoization on (index, running sum) makes it comfortably fast. But there is a cleaner way that turns the problem into something you already know.

Split the numbers into two groups: the ones that get a plus sign, with sum P, and the ones that get a minus sign, with sum N. The expression equals P - N, and every number lands in exactly one group, so P + N = total. Adding these two equations gives 2P = total + target, so P = (total + target) / 2. In other words, every valid sign assignment corresponds to exactly one subset of the numbers whose sum is (total + target) / 2, and vice versa.

That means the answer is the number of subsets with a particular sum, which is the classic 0/1 knapsack counting problem. If total + target is odd or negative, no such subset exists and the answer is 0. Otherwise keep an array dp where dp[j] counts the subsets seen so far that sum to j. Start with dp[0] = 1 for the empty subset. For each number, every existing subset that sums to j - num can be extended by that number to sum to j. Updating j from high to low ensures each number is used at most once per subset.

Approach: Subset-sum counting with a 1D DP

  1. Compute total = sum(nums).
  2. If total + target is odd or negative, return 0, because the required positive-group sum would not be a non-negative integer.
  3. Set subset_sum = (total + target) // 2 and create dp of length subset_sum + 1 with dp[0] = 1.
  4. For each num, loop j from subset_sum down to num, adding dp[j - num] to dp[j].
  5. The descending order means dp[j - num] still holds the count from before this number was considered, so no number is reused.
  6. Return dp[subset_sum], the number of subsets, and therefore sign assignments, that reach the target.

Step-by-step example

nums = [1, 1, 1, 1, 1], target = 3
  1. total = 5, and 5 + 3 = 8 is even, so subset_sum = 4 and dp = [1, 0, 0, 0, 0].
  2. After the first 1, dp = [1, 1, 0, 0, 0]. After the second, dp = [1, 2, 1, 0, 0].
  3. After the third 1, dp = [1, 3, 3, 1, 0]. After the fourth, dp = [1, 4, 6, 4, 1].
  4. After the fifth 1, dp = [1, 5, 10, 10, 5].
  5. The function returns dp[4] = 5. That matches the five ways to choose which single 1 gets the minus sign.

Code: Python, Java, C++

1class Solution:
2    def findTargetSumWays(self, nums: List[int], target: int) -> int:
3        total = sum(nums)
4
5        # (total + target) must be even and non-negative
6        if (total + target) % 2 != 0 or total + target < 0:
7            return 0
8
9        subset_sum = (total + target) // 2
10        dp = [0] * (subset_sum + 1)
11        dp[0] = 1
12
13        for num in nums:
14            for j in range(subset_sum, num - 1, -1):
15                dp[j] += dp[j - num]
16
17        return dp[subset_sum]

Time and space complexity

Time

O(n × S)

S is (total + target) / 2. For each of the n numbers, the inner loop runs over at most S + 1 sums with constant work per sum.

Space

O(S)

Only the single dp array of length S + 1 is kept, because each row of the knapsack table depends only on the previous row and the backward loop reuses it in place.

Other approaches

DFS with memoization (time O(n × total), space O(n × total))

Recurse on (index, current sum), trying plus and minus for each number, and cache results in a dictionary. It follows the problem statement directly and needs no algebra, but it stores a state for every reachable sum at every index.

Plain backtracking (time O(2^n), space O(n))

Try both signs for every number without caching and count the paths that end at the target. It is the easiest to write and passes for n up to 20, but it grows exponentially.

Common mistakes

  • Looping j upward in the 1D DP. That lets a number be added to a subset that already includes it, which counts combinations with repetition.
  • Skipping the parity and sign check. If total + target is odd or negative, integer division silently produces a wrong subset sum, and a negative size crashes the array allocation.
  • Mishandling zeros. A 0 can be +0 or -0, doubling the count. The reference loop handles it because for num = 0 the range includes j = 0, so dp[0] doubles; a loop that stops at j = 1 would miss this.
  • Not guarding against abs(target) > total in other languages. The reference code handles it implicitly since dp[subset_sum] stays 0, but some variants index out of range.

Frequently asked questions

How does Target Sum become a subset sum problem?

If P is the sum of numbers with plus signs and N the sum with minus signs, then P - N equals the target and P + N equals the total. Solving gives P = (total + target) / 2, so you count subsets with that sum.

Why does the inner loop go from high to low?

Going backward means dp[j - num] has not yet been updated for the current number, so each number contributes to a subset at most once. Going forward would turn it into an unbounded knapsack.

Is backtracking fast enough for Target Sum?

With at most 20 numbers, 2^20 is about a million paths, so plain backtracking usually passes. The DP is still preferred because it scales with the sum instead of exponentially with n.