GeeksforGeeks Medium

Subset Sum Equals Target

Subset Sum Equals Target is a GFG problem (Medium). You get an array arr of positive integers and a number sum. Return true if some of the elements, each used at most once, add up to exactly sum, and false otherwise.

  • You only answer yes or no. The elements themselves are not returned.
  • sum is at most 10,000, so a table with one cell per possible total is small. Trying every subset of 200 elements is not an option.
Constraints
  • 1 <= arr.length <= 200
  • 1 <= arr[i] <= 200
  • 1 <= sum <= 10^4
dpknapsackarray
Open on GeeksforGeeks ↗
02

Intuition

Track which totals can be reached instead of listing subsets. Keep a yes/no array can with one cell for every total from 0 to sum. At the start only 0 is reachable: picking nothing gives 0.

When an element x arrives, every total you could already reach can now be pushed up by x. So cell t turns on when cell t − x was already on. After the last element, can[sum] is the answer.

  • Walk from high totals to low: the cell you read, t − x, has then not been touched for x yet, so x is counted at most once.
  • Why it is fast: each element costs at most sum + 1 checks, however many subsets exist.
How to spot this pattern

This is the classic subset sum problem: each item is either taken once or left out, and the question is whether a total can be hit exactly. That is the 0/1 knapsack shape with only yes/no values, and the total is small enough to index an array.

03

Approach

Try it first

Before reading on, decide what one cell of the table should mean, and what a single new element can change in it. Then check your update with arr = [3] and sum = 6: the answer must be false. Aim for O(n · sum) time and O(sum) space.

1

Start with only zero reachable

Create can of length sum + 1, all false, and set can[0] = true. The empty pick reaches 0, and every other total has to be built from it by adding elements one at a time.

2

Add one element at a time

For each x, walk t from sum down to x. If can[t - x] is true, set can[t] to true, because the pick that reached t - x plus x reaches t. Totals below x cannot include x, so the walk stops there.

3

Skip elements that are too big

When x is larger than sum, the range from sum down to x is empty and nothing changes. No special case is needed: no total that matters can contain that element.

4

Stop as soon as the target is on

After each element, return true if can[sum] is on. Later elements only switch more cells on and never switch one off, so the answer cannot change. If the loop ends first, return can[sum], which is then false.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isSubsetSum(self, arr, sum):
▶3 can = [False] * (sum + 1)
▶4 can[0] = True
▶5 for x in arr:
▶6 for t in range(sum, x - 1, -1):
▶7 if can[t - x]:
▶8 can[t] = True
▶9 if can[sum]:
▶10 return True
▶11 return can[sum]
items342reachtotalyes0no1no2no3no4no5no6start: only 0 is reachable
sum6target total
reachable{0}
One cell per total from 0 to 6. Picking no elements gives a total of 0, so cell 0 starts as yes. Every other total has to be built from it by adding elements.
items3x42+3reachtotalyes0no1no2no3no4no5no63 not reachable → 6 stays no
x3
t6reads cell 3
reachable{0}
No pick reaches 3, so adding 3 cannot reach 6. Cell 6 stays no.
items3x42+3reachtotalyes0no1no2no3no4no5no62 not reachable → 5 stays no
x3
t5reads cell 2
reachable{0}
No pick reaches 2, so adding 3 cannot reach 5. Cell 5 stays no.
items3x42+3reachtotalyes0no1no2no3no4no5no61 not reachable → 4 stays no
x3
t4reads cell 1
reachable{0}
No pick reaches 1, so adding 3 cannot reach 4. Cell 4 stays no.
items3x42+3reachtotalyes0no1no2yes3no4no5no60 is reachable, add 3 → 3 is too
x3
t3reads cell 0
reachable{0, 3}
Cell 0 is yes, so some pick reaches 0. Adding 3 to that pick reaches 3. Cell 0 is below 3 and has not been touched for 3 yet, so this pick uses 3 once.
items34x2+4reachtotalyes0no1no2yes3no4no5no62 not reachable → 6 stays no
x4
t6reads cell 2
reachable{0, 3}
No pick reaches 2, so adding 4 cannot reach 6. Cell 6 stays no.
items34x2+4reachtotalyes0no1no2yes3no4no5no61 not reachable → 5 stays no
x4
t5reads cell 1
reachable{0, 3}
No pick reaches 1, so adding 4 cannot reach 5. Cell 5 stays no.
items34x2+4reachtotalyes0no1no2yes3yes4no5no60 is reachable, add 4 → 4 is too
x4
t4reads cell 0
reachable{0, 3, 4}
Cell 0 is yes, so some pick reaches 0. Adding 4 to that pick reaches 4. Cell 0 is below 4 and has not been touched for 4 yet, so this pick uses 4 once.
items342x+2reachtotalyes0no1no2yes3yes4no5yes64 is reachable, add 2 → 6 is too
x2
t6reads cell 4
reachable{0, 3, 4, 6}
Cell 4 is yes, so some pick reaches 4. Adding 2 to that pick reaches 6. Cell 4 is below 6 and has not been touched for 2 yet, so this pick uses 2 once.
items342x+2reachtotalyes0no1no2yes3yes4yes5yes63 is reachable, add 2 → 5 is too
x2
t5reads cell 3
reachable{0, 3, 4, 5, 6}
Cell 3 is yes, so some pick reaches 3. Adding 2 to that pick reaches 5. Cell 3 is below 5 and has not been touched for 2 yet, so this pick uses 2 once.
items342x+2reachtotalyes0no1no2yes3yes4yes5yes62 not reachable → 4 stays no
x2
t4reads cell 2
reachable{0, 3, 4, 5, 6}
No pick reaches 2, so adding 2 cannot reach 4. Cell 4 stays no.
items342x+2reachtotalyes0no1no2yes3yes4yes5yes61 not reachable → 3 stays no
x2
t3reads cell 1
reachable{0, 3, 4, 5, 6}
No pick reaches 1, so adding 2 cannot reach 3. Cell 3 stays no.
items342x+2reachtotalyes0no1yes2yes3yes4yes5yes60 is reachable, add 2 → 2 is too
x2
t2reads cell 0
reachable{0, 2, 3, 4, 5, 6}
Cell 0 is yes, so some pick reaches 0. Adding 2 to that pick reaches 2. Cell 0 is below 2 and has not been touched for 2 yet, so this pick uses 2 once.
items342xreachtotalyes0no1yes2yes3yes4yes5yes66 is reachable → return true
can[sum]true
Cell 6 is yes. Later elements can only switch more cells on, never off, so the answer is already true and the loop stops here.
05

Take-or-skip recursion with memo

can(i, left) asks whether the elements from index i onward can add up to left. Taking arr[i] is only tried when it fits in left. Each (i, left) pair is computed once and cached, which turns 2^n paths into at most n · sum states.

▶1from functools import lru_cache
▶2 
▶3 
▶4class Solution:
▶5 def isSubsetSum(self, arr, sum):
▶6 n = len(arr)
▶7 
▶8 @lru_cache(maxsize=None)
▶9 def can(i, left):
▶10 if left == 0:
▶11 return True
▶12 if i == n:
▶13 return False
▶14 if arr[i] <= left and can(i + 1, left - arr[i]):
▶15 return True
▶16 return can(i + 1, left)
▶17 
▶18 return can(0, sum)
06

Common pitfalls

Walking the totals upward

✗ Wrong
for t in range(x, sum + 1):
    if can[t - x]:
        can[t] = True
✓ Right
for t in range(sum, x - 1, -1):
    if can[t - x]:
        can[t] = True

With arr = [3] and sum = 6, the upward walk turns on 3, then reads that fresh 3 and turns on 6, so it returns true. It used the single 3 twice. That loop solves the version where every element can repeat, like coin change.

Forgetting that zero is reachable

✗ Wrong
can = [False] * (sum + 1)
✓ Right
can = [False] * (sum + 1)
can[0] = True

Every reachable total is built by adding to an earlier one, and the chain has to start at the empty pick. Without can[0], nothing ever turns on, so arr = [5] with sum = 5 returns false.

07

Edge cases

sum is the total of the whole array

The last element turns can[sum] on, so [1, 2, 3] with sum = 6 returns true. Taking every element is a valid subset.

Every element is bigger than sum

No inner loop runs, only can[0] is on, and the function returns false, as for [7, 8] with sum = 5.

08

Complexity

Time
O(n · sum)
Space
O(sum)
Each of the n elements checks at most sum + 1 cells, which is at most 2 million checks here. The textbook subset sum DP uses a 2D table dp[i][t] with the same 2 million cells, but each row only reads the row before it, so one array is enough.
09

Subset Sum Equals Target FAQ

Why is this called pseudo-polynomial time?

The running time grows with the value of sum, not with how many digits it has. With sum up to 10,000 that is cheap, but a target near 10^18 would need an impossible table. In general, subset sum is NP-complete, so no known method is polynomial in the input size.

How do I find which elements make the target?

Keep the full 2D table, where dp[i][t] says whether the first i elements can reach t. Start at (n, sum) and walk back: if dp[i - 1][t] is already true, element i is not needed; otherwise take arr[i - 1] and move to t - arr[i - 1]. Stop when t reaches 0.

How is this different from Subset Sums and Partition Equal Subset Sum?

Subset Sums lists the total of every subset, all 2^n of them, so it has to enumerate. Here only one total matters, so a table of totals replaces the list. Partition Equal Subset Sum is this same check with sum set to half of the array total.