Home
DSA Visualizer
Dynamic Programming
Subset Sum
Subset Sum Visualization
The Subset Sum problem asks whether some subset of a set of non-negative integers adds up exactly to a target value. Step through it in the interactive Subset Sum visualization below.
READY
0
1
2
3
4
5
Ø
2
3
5
Initialize DP table. Base case: Sum 0 is always possible (True).
Next
Checking sum 1 with item 2
Target Sum
Intuition
Imagine you have a set of coins and you want to know if you can pay an exact amount. For each coin, you have two choices: include it in your payment or exclude it. If you exclude it, you still need to make the full amount with the remaining coins. If you include it, you need to make (Target - CoinValue) with the remaining coins.
Concept
Boolean Dynamic Programming:
We define dp[i][j] as a boolean value: Is it possible to create a sum of j using a subset of the first i items?
Recurrence Relation:
- Exclude item i: Possible if
dp[i-1][j]is true. - Include item i (if nums[i] <= j): Possible if
dp[i-1][j - nums[i]]is true.
Result: dp[i][j] = dp[i-1][j] OR dp[i-1][j - nums[i]]
How Subset Sum Works
Tabulation Algorithm:
- Initialize a boolean table
dpof size (n+1) × (Target+1). - Base Case:
dp[i][0] = truefor all i (sum 0 is always possible with empty set). - Iterate through items i from 1 to n.
- Iterate through target sum j from 1 to Target.
- Apply the recurrence relation.
- The result is in
dp[n][Target].
Subset Sum Visualization, Step by Step
Visualizing the boolean table:
- True (T): Sum is reachable.
- False (F): Sum is not reachable.
- Propagation: 'True' values propagate down (exclusion) and diagonally right (inclusion).
When to Use
Applications:
- Decision problems involving sums.
- Load balancing (splitting tasks into two equal time sets).
- Cryptography (related to Knapsack cryptosystems).
When NOT to Use
- Large Target: If Target is huge, O(N*Target) is too slow.
- Floating Point Numbers: DP works best with integers/discrete steps.
How to Identify
"Does a subset sum to K?", "Can we partition into two equal sums?" (Partition Equal Subset Sum).
Practice it on interview problems
LeetCode problems solved with the Dynamic Programming pattern, each with a step-by-step visualizer:
All Dynamic Programming problemsApplying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
