LeetCode #494 Medium

Target Sum

Target Sum is LeetCode 494 (Medium). Put a + or a - in front of every number in nums and add everything up. Return how many sign choices give exactly target.

  • Every number gets a sign, including zeros; +0 and -0 count as different choices.
  • The numbers add up to at most 1,000, and that small total is what makes a table of sums cheap.
Constraints
  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums[i]) <= 1000
  • -1000 <= target <= 1000
dynamic-programmingarrayknapsack
Open on LeetCode ↗
02

Intuition

Split the numbers into the plus group, with sum P, and the minus group, with sum M. Then P − M = target and P + M = total. Adding the two equations gives

P = (total + target) / 2

So each valid sign choice is just a subset whose sum is (total + target) / 2: put + on its numbers and - on the rest. The task becomes counting subsets with a given sum, a 0/1 knapsack count.

If total + target is odd, or |target| > total, no whole-number P between 0 and total exists, and the answer is 0.

How to spot this pattern

Each item is either in or out (here, plus or minus) and you count the combinations that hit an exact total: that is a 0/1 knapsack count over sums.

03

Approach

Try it first

Before reading on, write the plus group's sum as P and the minus group's as M. Two facts link them to total and target. Solve for P and see what the question turns into. Aim for O(n · total).

1

Rule out impossible targets

Return 0 if |target| > total or if total + target is odd. In either case the plus group would need a negative, too large or fractional sum.

2

Start from the empty subset

Set plus = (total + target) / 2 and make ways of length plus + 1 with ways[0] = 1. Before any number is used, exactly one subset, the empty one, has sum 0.

3

Add the numbers one at a time

For each number x, for every s from plus down to x, add ways[s − x] into ways[s]. Each subset that reached s − x without x reaches s once x joins it.

4

Read the answer

ways[plus] is the number of subsets with sum plus, and each one stands for exactly one sign choice.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findTargetSumWays(self, nums, target):
▶3 total = sum(nums)
▶4 if abs(target) > total or (total + target) % 2:
▶5 return 0
▶6 plus = (total + target) // 2
▶7 ways = [1] + [0] * plus
▶8 for x in nums:
▶9 for s in range(plus, x - 1, -1):
▶10 ways[s] += ways[s - x]
▶11 return ways[plus]
nums121total4+target0=÷=plus groupwayssum 0sum 1sum 2beforeborrowedafter+=numbers add up to 4
total4
target0
Call the sum of the numbers that get + the plus group and the rest the minus group. Plus minus minus must equal 0, and plus plus minus is the total, 4. Adding the two facts: twice the plus group equals 4 + 0.
nums121total4+target0=4÷2=plus group2ways1sum 00sum 10sum 2beforeborrowedafter+=plus group needs sum 2
plus2
ways[1, 0, 0]
Half of 4 is 2, so the question becomes: how many subsets of the numbers add up to 2? Each such subset is one sign choice. Before any number is used, only the empty subset exists, so sum 0 has 1 way and every other sum has 0.
nums121total4+target0=4÷2=plus group2ways1sum 00sum 10sum 2beforeborrowedafter000+=sum 2: nothing to borrow → stays 0
x11st number
ways[2]0was 0
To reach 2 with this 1, the other numbers would need to make 1, and no subset of the numbers so far does. Sum 2 keeps 0.
nums121total4+target0=4÷2=plus group2ways1sum 01sum 10sum 2beforeborrowedafter011+=sum 1: 1 new way using the 1st number
x11st number
ways[1]1was 0
Every subset that made sum 0 without this 1 can add it to make 1. There is 1 such subset, so sum 1 goes from 0 to 1.
nums121total4+target0=4÷2=plus group2ways1sum 01sum 11sum 2beforeborrowedafter011+=sum 2: 1 new way using the 2nd number
x22nd number
ways[2]1was 0
Every subset that made sum 0 without this 2 can add it to make 2. There is 1 such subset, so sum 2 goes from 0 to 1.
nums121total4+target0=4÷2=plus group2ways1sum 01sum 12sum 2beforeborrowedafter112+=sum 2: 1 new way using the 3rd number
x13rd number
ways[2]2was 1
Every subset that made sum 1 without this 1 can add it to make 2. There is 1 such subset, so sum 2 goes from 1 to 2. Sum 1 has not been updated for this number yet, because sums are visited from high to low, so it cannot count it twice.
nums121total4+target0=4÷2=plus group2ways1sum 02sum 12sum 2beforeborrowedafter112+=sum 1: 1 new way using the 3rd number
x13rd number
ways[1]2was 1
Every subset that made sum 0 without this 1 can add it to make 1. There is 1 such subset, so sum 1 goes from 1 to 2.
nums121total4+target0=4÷2=plus group2ways1sum 02sum 12sum 2beforeborrowedafter+=2 subsets make 2 → 2 sign choices
ways[2]2
All numbers are in. 2 subsets add up to 2, and each one is a sign choice: its numbers get +, the others get −, and the result is 0. The answer is 2.
05

Memoized search over signs

count(i, total) is the number of ways to finish from index i when the numbers before it add up to total. It tries +nums[i] and -nums[i] and caches each answer. The running sum stays between -total and total, so there are at most n × (2 · total + 1) states.

▶1from functools import cache
▶2 
▶3class Solution:
▶4 def findTargetSumWays(self, nums, target):
▶5 @cache
▶6 def count(i, total):
▶7 if i == len(nums):
▶8 return 1 if total == target else 0
▶9 return count(i + 1, total + nums[i]) + count(i + 1, total - nums[i])
▶10 
▶11 return count(0, 0)
06

Common pitfalls

Walking the sums upward

✗ Wrong
for s in range(x, plus + 1):
    ways[s] += ways[s - x]
✓ Right
for s in range(plus, x - 1, -1):
    ways[s] += ways[s - x]

Going up, ways[s − x] may already include x, so the same number is used again. For [1, 1, 1, 1, 1] and target 3 this returns 70 instead of 5. Going down reads only counts from before x was added.

Skipping the range check

✗ Wrong
if (total + target) % 2:
    return 0
✓ Right
if abs(target) > total or (total + target) % 2:
    return 0

For nums = [1] and target −3, plus is −1. In Python ways[-1] quietly reads the last cell and returns 1; in C++ or Java the array size is 0 and the code crashes. The answer is 0.

07

Edge cases

Zeros in nums, such as [0, 0, 1] with target 1

Each zero doubles the count, so the answer is 4. The loop handles it because with x = 0 it runs down to s = 0 and adds ways[s] to itself.

08

Complexity

Time
O(n · total)
Space
O(total)
plus is at most total, which is at most 1,000, so there are at most 20 × 1,001 updates. The ways array has plus + 1 cells.
09

Target Sum FAQ

How is this related to Partition Equal Subset Sum?

Partition Equal Subset Sum asks whether some subset reaches total / 2, a yes-or-no question. Here the subset must reach (total + target) / 2 and you count them all. The table is the same; booleans become counts.

Can the minus group be counted instead?

Yes. The minus group needs sum (total − target) / 2, and the count of those subsets is the same answer. When target is positive this sum is smaller, so the array is shorter.