KatInterview

494. Target Sum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the number of ways to assign either a + or - sign to each number in an array nums such that the resulting sum of these numbers equals a given target.

Solution

Target Sum in Python

class Solution:
    def findTargetSumWays(self, nums: list[int], target: int) -> int:
        total_sum = sum(nums)

        # If the target is unreachable or the partitioning is impossible,
        # then there are no solutions.
        # 1. `total_sum < abs(target)` means the target is out of reach.
        # 2. `(total_sum + target)` must be even because it equals `2 * sum(P)`,
        #    where P is the subset of numbers with a positive sign.
        if abs(target) > total_sum or (total_sum + target) % 2 != 0:
            return 0

        # The problem is now transformed into finding a subset of nums
        # that sums up to `subset_sum`.
        subset_sum = (total_sum + target) // 2

        # dp[i] will be the number of ways to get sum i.
        dp = [0] * (subset_sum + 1)
        
        # There is one way to get sum 0: by choosing no elements.
        dp[0] = 1

        # Iterate through each number in the input array.
        for num in nums:
            # Iterate backwards to prevent using the same element multiple times in one subset.
            # This is a standard 0/1 knapsack-style DP update.
            for j in range(subset_sum, num - 1, -1):
                # The number of ways to form sum `j` is updated by adding the number
                # of ways to form sum `j - num` (by including the current `num`).
                dp[j] += dp[j - num]

        return dp[subset_sum]

Target Sum in Java

class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        int totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }

        // If the target is unreachable or the partitioning is impossible,
        // then there are no solutions.
        // 1. `totalSum < Math.abs(target)` means the target is out of reach.
        // 2. `(totalSum + target)` must be even because it equals `2 * sum(P)`,
        //    where P is the subset of numbers with a positive sign.
        if (Math.abs(target) > totalSum || (totalSum + target) % 2 != 0) {
            return 0;
        }

        // The problem is now transformed into finding a subset of nums
        // that sums up to `subsetSum`.
        int subsetSum = (totalSum + target) / 2;

        // dp[i] will be the number of ways to get sum i.
        int[] dp = new int[subsetSum + 1];
        
        // There is one way to get sum 0: by choosing no elements.
        dp[0] = 1;

        // Iterate through each number in the input array.
        for (int num : nums) {
            // Iterate backwards to prevent using the same element multiple times in one subset.
            // This is a standard 0/1 knapsack-style DP update.
            for (int j = subsetSum; j >= num; j--) {
                // The number of ways to form sum `j` is updated by adding the number
                // of ways to form sum `j - num` (by including the current `num`).
                dp[j] += dp[j - num];
            }
        }

        return dp[subsetSum];
    }
}

Target Sum in C++

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int target) {
        int totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }

        // If the target is unreachable or the partitioning is impossible,
        // then there are no solutions.
        // 1. `totalSum < abs(target)` means the target is out of reach.
        // 2. `(totalSum + target)` must be even because it equals `2 * sum(P)`,
        //    where P is the subset of numbers with a positive sign.
        if (abs(target) > totalSum || (totalSum + target) % 2 != 0) {
            return 0;
        }

        // The problem is now transformed into finding a subset of nums
        // that sums up to `subsetSum`.
        int subsetSum = (totalSum + target) / 2;

        // dp[i] will be the number of ways to get sum i.
        vector<int> dp(subsetSum + 1, 0);
        
        // There is one way to get sum 0: by choosing no elements.
        dp[0] = 1;

        // Iterate through each number in the input array.
        for (int num : nums) {
            // Iterate backwards to prevent using the same element multiple times in one subset.
            // This is a standard 0/1 knapsack-style DP update.
            for (int j = subsetSum; j >= num; --j) {
                // The number of ways to form sum `j` is updated by adding the number
                // of ways to form sum `j - num` (by including the current `num`).
                dp[j] += dp[j - num];
            }
        }

        return dp[subsetSum];
    }
};

Target Sum in TypeScript

function findTargetSumWays(nums: number[], target: number): number {
    let totalSum = nums.reduce((sum, num) => sum + num, 0);

    // If the target is unreachable or the partitioning is impossible,
    // then there are no solutions.
    // 1. `totalSum < Math.abs(target)` means the target is out of reach.
    // 2. `(totalSum + target)` must be even because it equals `2 * sum(P)`,
    //    where P is the subset of numbers with a positive sign.
    if (Math.abs(target) > totalSum || (totalSum + target) % 2 !== 0) {
        return 0;
    }

    // The problem is now transformed into finding a subset of nums
    // that sums up to `subsetSum`.
    const subsetSum = (totalSum + target) / 2;

    // dp[i] will be the number of ways to get sum i.
    const dp = new Array(subsetSum + 1).fill(0);

    // There is one way to get sum 0: by choosing no elements.
    dp[0] = 1;

    // Iterate through each number in the input array.
    for (const num of nums) {
        // Iterate backwards to prevent using the same element multiple times in one subset.
        // This is a standard 0/1 knapsack-style DP update.
        for (let j = subsetSum; j >= num; j--) {
            // The number of ways to form sum `j` is updated by adding the number
            // of ways to form sum `j - num` (by including the current `num`).
            dp[j] += dp[j - num];
        }
    }

    return dp[subsetSum];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.