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

The counting knapsack pattern

Lesson · 9 min read · Dynamic programming · Pattern: counting knapsack

Count the ways to reach a total. The single most important decision is whether order matters, and it is made by the order of the loops.

The pattern

Every knapsack pattern has a counting version: replace opt with sum, set the base case to 1 way of making 0, and add. The subtlety is what counts as "a way".

QuestionLoopsExample
combinations (order irrelevant), unlimiteditems outside, totals upwardsways to make change
ordered sequences, unlimitedtotals outside, items insideways to climb stairs with given steps
subsets, each item onceitems outside, totals downwardssubsets with a given sum
exactly k rolls or picksan extra dimension for kdice rolls with a target sum

Answers to counting problems grow quickly: check whether the problem asks for the count modulo 10⁹ + 7, and apply the modulus after every addition.

TimeO(items · target), times k for a fixed number of picks
SpaceO(target)

The problems in this module: