Target Sum is a classic dynamic programming problem that challenges you to find the number of ways to assign + and - signs to array elements to reach a target sum.

Given an integer array nums and an integer target, you need to build mathematical expressions by placing either a + or - sign before each number in the array. For example, with nums = [2, 1], you could create expressions like +2+1 = 3, +2-1 = 1, -2+1 = -1, or -2-1 = -3.

Your goal: Count how many different ways you can assign these signs to make the expression equal exactly target.

This problem beautifully combines backtracking, dynamic programming, and clever mathematical insights to transform what seems like an exponential problem into something much more manageable.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,1,1,1,1], target = 3
โ€บ Output: 5
๐Ÿ’ก Note: There are 5 ways to assign symbols to make the sum 3: -1 + 1 + 1 + 1 + 1 = 3, +1 - 1 + 1 + 1 + 1 = 3, +1 + 1 - 1 + 1 + 1 = 3, +1 + 1 + 1 - 1 + 1 = 3, +1 + 1 + 1 + 1 - 1 = 3
example_2.py โ€” Simple Case
$ Input: nums = [1], target = 1
โ€บ Output: 1
๐Ÿ’ก Note: Only one way: assign + to the single element to get +1 = 1
example_3.py โ€” Impossible Case
$ Input: nums = [1,2], target = 4
โ€บ Output: 0
๐Ÿ’ก Note: Maximum possible sum is 1+2=3, minimum is -(1+2)=-3. Target 4 is impossible to achieve.

Constraints

  • 1 โ‰ค nums.length โ‰ค 20
  • 0 โ‰ค nums[i] โ‰ค 1000
  • 0 โ‰ค sum(nums[i]) โ‰ค 1000
  • -1000 โ‰ค target โ‰ค 1000

Visualization

Tap to expand
Target Sum โ†’ Subset Sum TransformationPositive (+)Sum = P[1, 1, 1, 1]Negative (-)Sum = N[1]P - N = target = 3P + N = total = 5SolveP = (5 + 3) / 2 = 4Count subsets of [1,1,1,1,1] that sum to 4Dynamic Programming Solutiondp[0] = 1 (base case)For each number in [1,1,1,1,1]:Update dp[sum] += dp[sum - number]Final Answer: dp[4] = 5
Understanding the Visualization
1
Setup equations
If P = sum of positive numbers, N = sum of negative: P - N = target, P + N = total
2
Solve for P
Adding equations: 2P = total + target, so P = (total + target) / 2
3
Count subsets
Problem becomes: count subsets of nums that sum exactly to P
4
DP solution
Use classic subset sum DP: dp[i] = ways to make sum i
Key Takeaway
๐ŸŽฏ Key Insight: Transform the problem by recognizing that choosing which numbers to make positive is equivalent to finding subsets with a specific sum - this reduces exponential complexity to polynomial!
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 25 Apple 18
68.2K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen