Subset sum equals to target

Pattern: Subsequences and knapsack

medium

Can some subset add up to the target? Keep a table can[s]: whether sum s is reachable with the items seen so far. Each item makes s reachable if s - item was reachable before it; loop s downwards so each item is used once.

The problem

Given non-negative integers and a target, return whether some subset of them sums exactly to the target.

Think first

  • For each item, what are the two choices?
  • What do you need to remember about the items so far?
  • How big is the table?

Hints

    Brute force, and why it fails

    Try all 2ⁿ subsets.

    The key insight

    Only the set of reachable sums matters, and it has at most target + 1 values.

    Dry run

    reach0

    arr [1, 2, 3, 4], target 4. Start: only 0 is reachable.

    Step 1 of 3

    The plan

    can = [true, false, ...]
    for x: for s from target down to x: can[s] = can[s] or can[s - x]
    return can[target]
    

    Complexity

    Time
    O(n × target)
    Space
    O(target)

    One boolean row updated per item.

    Edge cases

    • Target 0: true.
    • An item larger than the target.
    • Zeros in the array.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isSubsetSum(int[] arr, int target) {
            boolean[] can = new boolean[target + 1];    // can[s]: some subset of the values so far adds up to s
            can[0] = true;                          // the empty subset
            for (int x : arr)
                for (int s = target; s >= x; s--) if (can[s - x]) can[s] = true;   // downwards, so x is used at most once
            return can[target];
        }
    }

    C++

    class Solution {
    public:
        bool isSubsetSum(vector<int>& arr, int target) {
            vector<bool> can(target + 1, false);    // can[s]: some subset of the values so far adds up to s
            can[0] = true;                          // the empty subset
            for (int x : arr)
                for (int s = target; s >= x; s--) if (can[s - x]) can[s] = true;   // downwards, so x is used at most once
            return can[target];
        }
    };

    Python

    class Solution:
        def isSubsetSum(self, arr: list[int], target: int) -> bool:
            can = [True] + [False] * target         # can[s]: some subset of the values so far adds up to s
            for x in arr:
                for s in range(target, x - 1, -1):  # downwards, so x is used at most once
                    if can[s - x]:
                        can[s] = True
            return can[target]

    Common mistakes

    • Looping s upwards, which reuses an item.
    • Starting with can[0] = false.

    Similar problems