KatInterview

Sample Size for A/B Tests and Bayesian Inference

Statistics & ExperimentsModel answer
HardModel answerStatistics & Experimentshypothesis-testingbayesian-inferencepower-analysis

Last updated

Calculate per-group sample size for a two-sample z-test given power requirements, and compute a Bayesian posterior probability.

You need to build two statistical functions for an experimentation platform.

Part A: Sample Size Calculation

Given historical data for a metric, determine how many observations are needed per variant in an A/B experiment.

Inputs:

  • observations: array of historical metric values (independent, identically distributed)
  • alpha: significance threshold (probability of false positive)
  • power: target probability of detecting a real effect
  • effect_size: minimum meaningful difference between variants (absolute value, same units as the metric)

Requirements:

  • Calculate the per-variant sample size for a two-sample z-test (two-tailed)
  • Assume equal allocation between control and treatment
  • Assume both variants have equal variance
  • Estimate population variance from the historical data
  • Return the smallest integer sample size that meets the power requirement

Part B: Posterior Probability

Given prior and conditional probabilities, calculate the posterior probability of an event.

Inputs:

  • prior: P(A)
  • likelihood: P(B|A)
  • likelihood_complement: P(B|¬A)

Return: P(A|B)

All probabilities are valid values in (0, 1).

Write clean, production-ready code with appropriate error handling.

Hints

Hint 1

For the sample size problem, start from the standard error of the difference between two means and work through what rejection threshold is needed

Hint 2

Remember that a two-tailed test splits the significance level between both tails

Hint 3

For Bayes' rule, you'll need to expand P(B) using the law of total probability