Payments app~25 min2s · 256 MBtarget O(number of distinct bundles × n) time, O(n) spaceclassic twin: lc-90backtracking
A wallet app holds coupons, each with a face value in units. Several coupons can have the same value, and coupons with the same value are interchangeable.
A shop accepts a bundle of coupons only when the face values add up to a multiple of its checkout step. The empty bundle adds up to 0, which counts as a multiple.
You count the different bundles that the shop would accept. Two bundles are the same when they hold the same values the same number of times.
Write count_distinct_bundles(coupons, modulus).
coupons[i] is the face value of coupon i. Equal values can repeat.modulus.Input: coupons = [1,1,2], modulus = 3
Output: 2The solution sorts the coupons and builds bundles one coupon at a time. At each level it skips a coupon whose value equals the one it tried immediately before, so each different bundle is built once.
| Bundle | Total | Multiple of 3 |
|---|---|---|
| empty | 0 | yes |
[1] |
1 | no |
[1,1] |
2 | no |
[1,1,2] |
4 | no |
[1,2] |
3 | yes |
[2] |
2 | no |
Two bundles are accepted, so the answer is 2. The three coupons have 8 subsets, but [1] and [1,2] each appear twice among them.
Input: coupons = [5,5,5,5], modulus = 5
Output: 5The bundles hold zero, one, two, three or four coupons of value 5. That is 5 different bundles, and each total is a multiple of 5.
Input: coupons = [4,6,6,9], modulus = 10
Output: 2The empty bundle adds up to 0, and [4,6] adds up to 10. There are two coupons of value 6, but [4,6] is one bundle, so it counts once.
1 ≤ len(coupons) ≤ 22, and 1 ≤ coupons[i] ≤ 1,0001 ≤ modulus ≤ 1,000Twenty-two coupons have 2 to the power of 22 subsets, which is 4,194,304. When values repeat, many subsets are the same bundle. Skipping a repeat at each level builds each different bundle once, so a wallet with few distinct values has far fewer bundles than subsets.