KatInterview

Calculate Sample Size per Variant for A/B Testing

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashingstatisticsa-b-testinghypothesis-testing

Last updated

Compute the minimum sample size required per group for a two-sample z-test given standard deviation, MDE, power, and significance level.

In experimental design for online A/B testing, determining the correct sample size is essential to ensure that an experiment has sufficient statistical power to detect meaningful differences without over-allocating traffic.

Given an experiment with two equal-sized variants (treatment and control), calculate the minimum required sample size per variant for a two-sided two-sample z-test using standard normal quantiles.

The formula to compute the required number of units per group $n$ is:

$$n = \frac{2 \cdot \sigma^2 \cdot (z_{1 - \alpha/2} + z_{\text{power}})^2}{\delta^2}$$

Where:

  • $\sigma$ (std_dev) is the standard deviation of the metric.
  • $\delta$ (mde) is the minimum detectable effect size.
  • $z_{1 - \alpha/2}$ is the standard normal critical value for a two-tailed significance level $\alpha$.
  • $z_{\text{power}}$ is the standard normal critical value for the desired statistical power (power).
  • Note: baseline_mean is passed as an input parameter for context, but it does not alter the minimum sample size formula.

Calculate $n$ and return the smallest integer greater than or equal to $n$ (i.e., apply ceiling rounding math.ceil).

To compute standard normal quantiles ($z$-scores), use standard normal quantile calculations available in Python's standard library standard tools (such as statistics.NormalDist().inv_cdf).

Constraints

  • $1 \le \text{baseline_mean} \le 1000$
  • $0.1 \le \text{std_dev} \le 500.0$
  • $0.01 \le \text{mde} \le 100.0$
  • $0.5 \le \text{power} < 1.0$
  • $0.001 \le \text{alpha} < 0.5$

Examples

Example 1

Input: calculate_sample_size_per_group(120, 40, 3, 0.8, 0.05)

Output: 2791

Example 2

Input: calculate_sample_size_per_group(120, 40, 5, 0.8, 0.05)

Output: 1005

Example 3

Input: calculate_sample_size_per_group(120, 40, 3, 0.9, 0.05)

Output: 3736

Example 4

Input: calculate_sample_size_per_group(120, 40, 3, 0.8, 0.01)

Output: 4153