DSA interview question
You're building a "portfolio scenario counter" for a trading-simulation tool. Each entry in an array nums represents a trade's magnitude, but every trade could have gone either long (+) or short (-) — the historical direction wasn't logged, only the magnitudes. Given the array nums and a known final net target, your job is to count how many distinct sign assignments (one + or - per element) result in an expression that sums exactly to target. This tells the risk team how many plausible historical scenarios could explain the observed final outcome.
int findTargetSumWays(vector<int>& nums, int target);
nums | target | Output | Explanation |
|---|---|---|---|
[1,1,1,1,1] | 3 | 5 | 5 distinct sign assignments sum to 3 (e.g. +1+1+1+1-1, and 4 other permutations of one minus) |
[1] | 1 | 1 | only +1 works |
[1] | 2 | 0 | impossible — max achievable magnitude is 1 |
[0,0,0,0,0,0,0,0,1] | 1 | 256 | each 0 can independently be + or - (no effect), giving 2^8 = 256 combinations, all valid |
[] | 0 | 1 | empty array, target 0 → one way: the empty assignment |
[100] | -100 | 1 | only -100 works |
[1,2,3] | 0 | 2 | +1+2-3 and -1-2+3 |
(Watch the [0,0,...,0,1] case — it's a classic trap testing whether your subset-sum reduction correctly handles zero-valued elements, which double the count of every valid subset they're added to.)
nums[i] >= 0; the sign is what you're choosing, not an inherent property of the input.)target be negative?nums and magnitude of values? (Signals whether brute-force 2^n recursion needs to become DP, and what capacity range the DP subset-sum table needs.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in