Target Sum
Problem
You are given a list of non-negative integers nums and an integer target. For every element you must choose a sign, + or -, and then add up the signed values. Count how many distinct sign assignments make the total equal to target. Two assignments are different if they differ in the sign of at least one position, even when the element values are equal.
numsholds up to twenty non-negative integers, and their sum stays within a moderate range (at most a thousand or so).targetcan be negative and is within the same rough magnitude.
Examples
nums = [2, 2, 2, 2, 2], target = 2→10. Exactly two of the five 2s get a minus sign, since10 - 2*(2+2) = 2, and there areC(5, 2) = 10ways to choose which two.nums = [3], target = 3→1. Only+3works.nums = [2, 3], target = 6→0. The largest achievable total is 5.
Hints
- Separate the elements into the ones you add and the ones you subtract. Write the total in terms of the sum of each group.
- Since the two groups together sum to
sum(nums), the total is determined entirely by the sum of the positive group. What must that sum be? - Count the subsets with sum
(sum(nums) + target) / 2using 0/1 knapsack counting with the inner loop descending.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.