AlgoInsight

DSA problem

Target Sum

Medium0/1 KnapsackPattern: 0/1 Knapsacktop150AmazonGoogleFacebookMicrosoftBloomberg

You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols + or - before each integer in nums and then concatenating all the integers. Return the number of different expressions that you can build, which evaluates to target.

A naive recursive search tries both + and - for each element and counts the leaves whose running sum equals target. That tree has 2^n paths, so direct enumeration is exponential and intractable beyond about 20 elements. Memoization on (index, current_sum) brings it down to polynomial, but a cleaner formulation removes the search entirely.

Split nums into two disjoint subsets P (elements assigned +) and N (elements assigned -). Then the expression evaluates to sum(P) - sum(N) = target, and we also have sum(P) + sum(N) = sum(nums). Adding those equations gives sum(P) = (sum(nums) + target) / 2. So the original problem reduces to: count the number of subsets of nums whose sum equals this derived value P.

This is a classic 0/1 knapsack counting problem. If (sum + target) is negative or odd, the answer is 0. Otherwise we run a 1D DP where dp[s] is the number of subsets that sum to s. We initialize dp[0] = 1 (one way to get sum 0: the empty subset) and for each num iterate the capacity dimension from P down to num so each element is used at most once. The final answer is dp[P], computed in O(n * P) time using O(P) space.

Examples

Example 1
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign signs: -1+1+1+1+1, +1-1+1+1+1, +1+1-1+1+1, +1+1+1-1+1, +1+1+1+1-1.
Example 2
Input: nums = [1], target = 1
Output: 1
Explanation: The only expression evaluating to 1 is +1 itself.
Example 3
Input: nums = [1,2,1], target = 0
Output: 2
Explanation: Two assignments work: +1-2+1 and -1+2-1, both evaluate to 0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dynamic-programming0-1-knapsacksubset-sumarray

Browse all DSA problems