KatInterview

Experiment Sizing and Beta Posterior Update

Arrays & HashingAuto-graded · 14 test cases
EasyAuto-gradedArrays & Hashingstatisticspower-analysisbayesian-update

Last updated

Compute the per-group sample size for a two-proportion test from a given formula, and update a Beta prior with observed Bernoulli outcomes.

Experiment Sizing and Beta Posterior Update

You are planning a two-group experiment on a conversion rate and, separately, updating a belief about the conversion rate of a different user segment. Write a single function that handles both calculations.

Part 1: Sample size per group

You are given:

  • baseline_rate (p): the current conversion rate.
  • target_rate (p_alt): the conversion rate you want to be able to detect.
  • z_alpha: the critical value for the two-sided significance level.
  • z_beta: the critical value for the desired power.

The required number of users in each group is

n = (z_alpha * sqrt(2 * p * (1 - p)) + z_beta * sqrt(p * (1 - p) + p_alt * (1 - p_alt)))^2 / (p_alt - p)^2

Compute n in floating point using the given z_alpha and z_beta values as they are, with no intermediate rounding. Then round the final value up to the next integer (the ceiling). This integer is the sample size per group.

Part 2: Beta posterior

A Beta prior with parameters prior_a and prior_b describes the conversion probability of a user segment. You then observe num_users independent users, of whom num_converted converted. The posterior is again a Beta distribution with:

  • posterior_alpha = prior_a + num_converted
  • posterior_beta = prior_b + (num_users - num_converted)

Output

Return a dictionary with exactly these three integer entries:

{
  "sample_size_per_variant": <ceil of n>,
  "posterior_alpha": <updated alpha>,
  "posterior_beta": <updated beta>
}

Constraints

  • 0 < baseline_rate < 1 and 0 < target_rate < 1.
  • target_rate != baseline_rate.
  • z_alpha and z_beta are positive floats.
  • prior_a and prior_b are positive integers.
  • 0 <= num_converted <= num_users.
  • Observations are independent.
  • The sample size is a per-group count, not a total across groups.

Examples

Example 1

Input: plan_test_and_update_beta(0.05, 0.055, 1.96, 0.84, 2, 18, 100, 8)

Output: {'sample_size_per_variant': 30210, 'posterior_alpha': 10, 'posterior_beta': 110}

Example 2

Input: plan_test_and_update_beta(0.1, 0.11, 1.96, 0.84, 1, 1, 10, 1)

Output: {'sample_size_per_variant': 14297, 'posterior_alpha': 2, 'posterior_beta': 10}

Hints

Hint 1

Evaluate the formula directly in floating point and apply math.ceil only once, to the final value.

Hint 2

The null-hypothesis term uses 2*p*(1-p), while the alternative term adds the variances of both rates: p*(1-p) + p_alt*(1-p_alt).

Hint 3

For the Beta-Bernoulli update, successes are added to the first parameter and failures (users minus conversions) are added to the second, not the total number of users.