1521. Distinct Draws Expectation

Medium3.5 points estimatedProbabilityHash TableMaths

A lucky-dip bag contains tokens, each stamped with a label. The map bag gives, for every label, how many tokens carry it; let N be the total number of tokens. A player draws one token uniformly at random, notes its label, puts it back, and repeats this draws times in total, all draws being independent.

Return the expected number of distinct labels the player notes. The answer is accepted within an absolute or relative error of 1e-6. Use linearity of expectation over labels; a numerically careful evaluation of 1 - (1 - c / N)^draws avoids losing precision when c / N is tiny. Aim for O(L) time for L labels.

Example 1

Input:
bag = {"1":1,"2":1}, draws = 2
Output:
1.5
Explanation:
Each draw shows either label with probability 1/2, so the expected distinct count is 2 * (1 - 1/4) = 1.5.

Example 2

Input:
bag = {"7":3}, draws = 5
Output:
1
Explanation:
Only one label exists, so exactly one distinct label is always seen.

Example 3

Input:
bag = {"3":1,"4":1,"9":2}, draws = 3
Output:
2.03125
Explanation:
The labels are seen with probabilities 1 - (3/4)^3, 1 - (1/2)^3 and 1 - (3/4)^3, which total 2.03125.

Constraints

1 ≤ number of labels L ≤ 104

1 ≤ count of every label ≤ 105, and the total number of tokens N is at most 109

1 ≤ draws ≤ 109

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001

Expected complexity

Time
O(L)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…