Skip to content

ORIGINAL CODING QUESTION

Distinct voucher collections

A campus store has n gift vouchers with positive values, and several vouchers can share a value. Each voucher can be used at most once. Count the different collections of voucher VALUES that add up exactly to the target. Two collections are the same when they contain every value the same number of times, no matter which physical vouchers were used.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n voucher values, then target. Print the number of distinct collections.

Constraints

1 ≤ n ≤ 12; 1 ≤ value ≤ 50; 1 ≤ target ≤ 600.

Example 1

Input

5
2 1 2 3 1
4

Output

3

The distinct collections are {1,3}, {2,2} and {1,1,2}.

Example 2

Input

4
3 3 3 3
6

Output

1

Any two vouchers form the same collection {3,3}, so it counts once.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Counting selections of positions would count {1,3} twice when there are two 1 vouchers.

Hint 2

Sort the values and build collections in nondecreasing order of position.

Hint 3

At one level of the recursion, skip a value equal to the previous value tried at that same level; this removes duplicate collections without a set.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →