Count expressions reaching a target sum
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Count expressions reaching a target sum states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= nums.length <= 20 (and the empty array is handled correctly)
- 0 <= nums[i] <= 1000
- 0 <= sum(nums) <= 1000
- -1000 <= target <= 1000
Examples
Input: ([1, 1, 1, 1, 1], 3)
Expected Output: 5
Explanation: Exactly one of the five 1's gets a minus sign; the other four are plus. 5 choices -> 5 assignments. s = (5+3)/2 = 4, and there are C(5,4)=5 subsets of size 4 summing to 4.
Input: ([1], 1)
Expected Output: 1
Explanation: Only +1 reaches 1. s = (1+1)/2 = 1; one subset {1} sums to 1.
Hints
- Split nums into a positive set P (assigned +) and a negative set N (assigned -). Then sum(P) - sum(N) = target and sum(P) + sum(N) = total.
- Adding the two equations gives sum(P) = (total + target) / 2. If (total + target) is odd or |target| > total, no assignment works -> return 0.
- Now the problem is 'count subsets of nums that sum to s = (total + target) / 2' — a classic 0/1-knapsack counting DP. Iterate j downward so each number is used at most once.
- Zeros need care: a zero can go in P or N without changing any sum, so each zero doubles the number of distinct assignments. The subset-sum DP captures this automatically because dp[j-0] = dp[j] adds the count of placing the zero.