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.
Input: ([1], 2)
Expected Output: 0
Explanation: |target| = 2 > total = 1, so no sign assignment can reach 2.
Input: ([100], -200)
Expected Output: 0
Explanation: |target| = 200 > total = 100; impossible.
Input: ([0, 0, 0, 0, 0, 0, 0, 0, 1], 1)
Expected Output: 256
Explanation: The 1 must be +. Each of the 8 zeros can be + or - freely, contributing 2^8 = 256 distinct assignments. s = (1+1)/2 = 1 and the DP multiplies by 2 per zero.
Input: ([2, 3, 5, 7, 9], 4)
Expected Output: 1
Explanation: s = (26+4)/2 = 15. The only subset summing to 15 is {3,5,7}, i.e. +3+5+7-2-9 = 4. So exactly 1 assignment.
Input: ([], 0)
Expected Output: 1
Explanation: Empty expression evaluates to 0; the one (empty) assignment matches. s = 0, dp[0] = 1.
Input: ([], 1)
Expected Output: 0
Explanation: Empty expression can only be 0, never 1. |target| > total = 0 -> 0.
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.