Algorithms · Visualized
DP: Subset Sum
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Determines if any subset of a given array of numbers sums to exactly a target value. Time: O(n × target) average, O(n × target) worst; space: O(target) — the dp array.
Big-O: The most-asked interview category — 35 classics here.
Subset Sum
Dynamic ProgrammingDetermines if any subset of a given array of numbers sums to exactly a target value. dp[s] tracks whether sum s is achievable using the numbers processed so far, updated for each number by checking if it can extend an already-achievable sum.
How Subset Sum Works
- Create a boolean DP array of size (target + 1), with dp[0] = true (a sum of 0 is always achievable using no elements).
- For each number in the array, update the dp array from the highest sum down to the number's own value (processing in this order prevents reusing the same number twice within one pass).
- For each sum s from target down to the number's value, set dp[s] to true if dp[s - number] was already true.
- Continue processing every number in the array this way.
- Return dp[target] — true if some subset of the array sums to exactly the target.
Subset Sum Worked Example
Input: {array: [3, 34, 4, 12, 5, 2], target: 9}
Start dp[0]=true. Process 3: dp[3]=true. Process 34: too big for target9, no change. Process 4: dp[7]=true (3+4), dp[4]=true. Process 12: too big, no change. Process 5: dp[9]=true (4+5), dp[5]=true, dp[8]=true(3+5). dp[9] is true — subset {4,5} sums to 9.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|---|
| none | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +34 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
def subset_sum(nums, target):
dp = [False] * (target + 1)
dp[0] = True
for v in nums:
for i in range(target, v - 1, -1):
if dp[i - v]:
dp[i] = True
return dp[target]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Subset Sum Time & Space Complexity
When to Use Subset Sum
- Foundational building block for Partition Equal Subset Sum and other 'can we reach this exact total' resource/budget problems.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.