Skip to content
StackDecode
Dynamic programmingAnimated

Subset Sum

Can some subset add up to the target?

Time

O(n · target)

Extra space

O(target)

Use it for

Budgeting, partitioning.

How it works

  1. Can some subset of the numbers add up to the target?
  2. Keep a row reach[s] = "is sum s possible?". Only reach[0] (empty subset) starts true.
  3. For each number x, any sum s that was reachable makes s + x reachable too. Update from high to low so x is used at most once.
  4. The answer is reach[target]. O(n × target).

Watch it run

Loading animation…