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

Can a subset reach the target?

Medium · Target 15 minutes · Dynamic programming

Given positive integers nums and a non-negative target, return true if some subset of nums (each element used at most once) sums to exactly target. The empty subset sums to 0.

Examples

InputOutputWhy
nums = [3,34,4,12,5,2], target = 9true4 + 5.
nums = [3,34,4,12,5,2], target = 30falseNo subset adds to 30.
nums = [2,4,6], target = 5falseOnly even totals are reachable.

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 100
  • 0 ≤ target ≤ 10⁴

Hints

Hint 1

reach[t] = can some subset of the numbers seen so far sum to t? reach[0] = true.

Hint 2

For each number x: reach[t] |= reach[t − x], for t from target down to x.

Hint 3

Downwards, so each number is used at most once.

Where people lose marks

  • Iterating totals upwards, which lets one number be used repeatedly.
  • Exponential backtracking without memoisation.
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.