Target Sum

Pattern: Subsequences and knapsack

medium

Put + or - before every number to reach the target. The + numbers P and - numbers N satisfy P - N = target and P + N = total, so P = (total + target) / 2: count subsets with that sum.

The problem

Return the number of ways to put + or - before each number so that the expression equals target.

Think first

  • How do the + and - groups relate to the total?
  • What is the + group's sum?
  • When is the answer 0?

Hints

    Brute force, and why it fails

    Try all 2ⁿ sign patterns.

    The key insight

    Signs split the numbers into two groups, so the count is the number of subsets with one sum.

    Dry run

    p4

    nums [1, 1, 1, 1, 1], target 3: total 5, so P = 4.

    Step 1 of 2

    The plan

    if |target| > total or (total + target) odd: 0
    return countSubsets(nums, (total + target) / 2)
    

    Complexity

    Time
    O(n × total)
    Space
    O(total)

    Counting subset sums.

    Edge cases

    • Zeros: each doubles the count.
    • Target larger than the total.
    • Negative target.
    I've built my logic, show the code

    Java

    class Solution {
        public int findTargetSumWays(int[] nums, int target) {
            int total = 0;
            for (int x : nums) total += x;
            if (Math.abs(target) > total || (total + target) % 2 != 0) return 0;
            int plus = (total + target) / 2;        // the numbers given a + sign must add up to (total + target) / 2
            int[] ways = new int[plus + 1];
            ways[0] = 1;
            for (int x : nums) for (int s = plus; s >= x; s--) ways[s] += ways[s - x];
            return ways[plus];
        }
    }

    C++

    class Solution {
    public:
        int findTargetSumWays(vector<int>& nums, int target) {
            int total = 0;
            for (int x : nums) total += x;
            if (abs(target) > total || (total + target) % 2 != 0) return 0;
            int plus = (total + target) / 2;        // the numbers given a + sign must add up to (total + target) / 2
            vector<int> ways(plus + 1, 0);
            ways[0] = 1;
            for (int x : nums) for (int s = plus; s >= x; s--) ways[s] += ways[s - x];
            return ways[plus];
        }
    };

    Python

    class Solution:
        def findTargetSumWays(self, nums: list[int], target: int) -> int:
            total = sum(nums)
            if abs(target) > total or (total + target) % 2:
                return 0
            plus = (total + target) // 2            # the numbers given a + sign must add up to (total + target) / 2
            ways = [1] + [0] * plus
            for x in nums:
                for s in range(plus, x - 1, -1):
                    ways[s] += ways[s - x]
            return ways[plus]

    Common mistakes

    • Forgetting zeros can take either sign.
    • Missing the parity check.

    Similar problems