Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Subsets with a given sum

Medium · Target 15 minutes · Dynamic programming

Given non-negative integers nums and a target, return the number of subsets (chosen by position, so equal values at different positions are different elements) whose sum is target. The empty subset sums to 0.

Examples

InputOutputWhy
nums = [1,1,2,3], target = 43{1, 3} with either 1, and {1, 1, 2}.
nums = [1,2,3,4,5], target = 53{5}, {1, 4}, {2, 3}.
nums = [0,0,1], target = 14Each 0 may be included or not.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 1000
  • 0 ≤ target ≤ 10⁴
  • The answer fits in a 64-bit integer

Hints

Hint 1

ways[t] = number of subsets of the elements seen so far that sum to t; ways[0] = 1.

Hint 2

For each element x, for t downwards: ways[t] += ways[t − x].

Hint 3

Zeros double every count: the downward loop handles them if it includes t = x = 0 correctly.

Where people lose marks

  • Iterating upwards, which reuses elements.
  • Mishandling zeros (each zero should double the count).
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.