A/B Test Sample Size and Runtime

Easy · Analytics & Experimentation · Data Scientist · Technical Screen

Problem Statement

An online retail team is preparing a randomized experiment on a redesigned "Express Checkout" button on product detail pages, measuring the purchase conversion rate across eligible shoppers.

Implement four helper functions to size and schedule a two-sided two-proportion z-test using only the Python standard library:

  1. z_score(prob: float) -> float Return the standard normal quantile z such that P(Z <= z) = prob for a standard normal variable Z ~ N(0, 1). Raise ValueError if prob is not strictly inside (0, 1).

  2. sample_size_per_group(baseline: float, relative_mde: float, alpha: float = 0.05, power: float = 0.80) -> int Compute the minimum whole number of users required in each arm of a two-sided two-proportion z-test:

    • Control conversion rate is p1 = baseline, and target variant conversion rate is p2 = baseline * (1 + relative_mde).
    • Approximate the single-user Bernoulli standard deviation using the pooled rate p = (p1 + p2) / 2 as sqrt(p * (1 - p)), giving: text n = (z_{1 - alpha/2} + z_{power})^2 * 2 * p * (1 - p) / (p2 - p1)^2
    • Round any fractional user count up to the next integer so statistical power never drops below power.
    • Raise ValueError if relative_mde == 0, or if p1, p2, alpha, or power lies outside (0, 1).
  3. experiment_days(n_per_group: int, daily_users: int, n_groups: int = 2) -> int Given daily_users newly eligible shoppers arriving per day and split evenly across n_groups experimental arms, return the minimum number of whole days required until every arm collects at least n_per_group users. Raise ValueError if n_per_group < 0, daily_users <= 0, or n_groups <= 0.

  4. plan_experiment(baseline: float, relative_mde: float, daily_users: int, alpha: float = 0.05, power: float = 0.80) -> Tuple[int, int] Return (users_per_group, days_needed) for a balanced two-arm (50/50) split.

Examples

Example 1

Input:  plan_experiment(baseline=0.08, relative_mde=0.125, daily_users=6000, alpha=0.05, power=0.80)
Output: (12209, 5)

With p1 = 0.08 and a +12.5% relative lift, p2 = 0.08 * 1.125 = 0.09 (+0.01 absolute lift) and the pooled rate is p = 0.085, giving 2 * p * (1 - p) = 0.15555. Summing z_score(0.975) ≈ 1.95996 and z_score(0.80) ≈ 0.84162 yields 2.80159 (2.80159^2 ≈ 7.84888), so raw per-arm size is 7.84888 * 0.15555 / 0.01^2 = 12208.93, which rounds up to 12209 users per arm (24418 across both arms). At 6000 eligible shoppers per day, 24418 / 6000 = 4.07 days, rounding up to 5 whole days.

Example 2

Input:  plan_experiment(baseline=0.08, relative_mde=0.0625, daily_users=6000, alpha=0.05, power=0.80)
Output: (47529, 16)

Halving the relative minimum detectable effect to +6.25% (p2 = 0.085, p2 - p1 = 0.005) divides (p2 - p1)^2 by 4. With pooled rate p = 0.0825, raw per-arm size rises roughly four-fold to 47528.89 -> 47529 users per arm (95058 total), taking ceil(95058 / 6000) = 16 whole days.

Example 3

Input:  experiment_days(n_per_group=15000, daily_users=9000, n_groups=3)
Output: 5

Three equal arms of 15000 users require 45000 shoppers overall. At 9000 shoppers per day, 45000 / 9000 = 5 exact days with no extra day added.

Constraints

  • Valid probability parameters (prob, baseline, baseline * (1 + relative_mde), alpha, and power) must satisfy 0.0 < x < 1.0; otherwise raise ValueError.
  • relative_mde may be positive (testing for a lift) or negative (testing for a drop), as long as relative_mde != 0.0 and 0.0 < baseline * (1 + relative_mde) < 1.0.
  • Valid schedule parameters satisfy n_per_group >= 0, daily_users >= 1, and n_groups >= 1; otherwise raise ValueError.
  • Use the normal distribution approximation and round fractional user and day requirements up to the next whole integer.

Step-by-step walkthrough

  1. Understand the scenario and inputs

    Each eligible shopper viewing a product detail page behaves like a single weighted coin flip (a Bernoulli trial): either they complete an "Express Checkout" purchase (1) or they do not (0). Before touching an equation, map every parameter in Example 1 to exact numbers:

    • Baseline conversion rate: the share of control shoppers who purchase, p1 = 0.080 (8.0%).
    • Minimum Detectable Effect (MDE): the smallest genuine improvement we design the experiment to catch reliably. A +12.5% relative lift multiplies the baseline by 1.125, giving a target variant rate of p2 = 0.080 * 1.125 = 0.090 (9.0%)—an absolute lift of delta = 0.090 - 0.080 = 0.010 (1.0 percentage point).
    • Significance level (alpha = 0.05, two-sided): our cap on false alarms—at most a 5% probability of declaring a winner (in either direction) when the new button truly changes nothing.
    • Statistical power (1 - beta = 0.80): our true-positive catch rate—an 80% probability of reaching statistical significance when the button truly lifts conversion to 9.0% (leaving a beta = 20% miss rate).
    Control rate (p1)  = 0.080 (8.0%)          Variant rate (p2) = 0.080 * 1.125 = 0.090 (9.0%)
    Absolute MDE       = +0.010 (+1.0 pp)      Pooled rate (p)   = (0.080 + 0.090) / 2 = 0.085
    Alpha (two-sided)  = 0.05                  Power (1 - beta)  = 0.80
    Eligible traffic   = 6,000 new users/day   50/50 split       = 3,000 users/arm/day
    

    Note one important traffic caveat: 6,000 daily shoppers means 6,000 newly randomized unique shoppers arriving per day. When repeat visitors browse across multiple days, unique shopper counts accumulate more slowly than raw daily session counts.

  2. Derive the sample-size formula from two normal bell curves

    Suppose we enroll n shoppers in Control and n shoppers in Variant, then measure the observed conversion difference diff_hat = p2_hat - p1_hat. Under the pooled single-user standard deviation sqrt(p * (1 - p)) where p = (p1 + p2) / 2, each arm's sample proportion has variance p * (1 - p) / n. Because the two arms are independent, the variance of their difference equals the sum of the two arm variances:

    Var(p2_hat - p1_hat) = p*(1 - p)/n + p*(1 - p)/n = 2 * p * (1 - p) / n
    Standard Error (SE)  = sqrt( 2 * p * (1 - p) / n )
    

    Now picture two normal bell curves of width SE—one centered at 0 (if the button has zero effect) and one centered at delta = +0.010 (if the button truly hits the MDE):

           Null curve (no effect, mean = 0)        Alternative curve (true lift, mean = delta)
                    _.-""""-._                                    _.-""""-._
                  .'          '.                                .'          '.
                .'              '.              |             .'              '.
       ________/                  \_____________|____________/                  \________
       -------+--------------------+------------+-----------+--------------------+-------> observed diff
              0                    |<---------->|<--------->|                  delta
                                 z_{1-alpha/2}*SE  z_{power}*SE
                                                ^
                                   Decision threshold (critical cutoff)
    
    1. Cap false positives (alpha = 0.05 two-sided): Placing alpha / 2 = 0.025 (2.5%) in the upper tail of the Null curve puts the decision threshold at z_{0.975} * SE above 0.
    2. Guarantee 80% power (1 - beta = 0.80): For 80% of the Alternative curve's mass to land above that threshold, the true mean delta must sit z_{0.80} * SE to the right of the threshold.

    Summing those two horizontal segments gives the distance from 0 to delta, which we solve step by step for n:

    delta = (z_{1 - alpha/2} + z_{power}) * SE
    delta = (z_{1 - alpha/2} + z_{power}) * sqrt(2 * p * (1 - p) / n)
    delta^2 = (z_{1 - alpha/2} + z_{power})^2 * 2 * p * (1 - p) / n
    n = (z_{1 - alpha/2} + z_{power})^2 * 2 * p * (1 - p) / delta^2
    

    (Using unpooled p1*(1 - p1) + p2*(1 - p2) instead of pooled 2 * p * (1 - p) yields 12,206 instead of 12,209—a difference of just 3 shoppers out of 12,209.)

  3. Compute standard normal quantiles and group sample size

    Python's standard library provides statistics.NormalDist().inv_cdf(prob), which evaluates the quantile (inverse cumulative distribution, i.e., the z-score leaving probability prob to its left) with no third-party dependencies.

    Validate boundary inputs explicitly (0 or 1 rates, zero MDE, or out-of-bounds alpha/power) and round the raw sample size up with math.ceil—rounding down even slightly would leave true power below 0.80:

    from typing import Tuple
    import math
    from statistics import NormalDist
    
    
    def _check_probability(name: str, value: float) -> None:
        """Validate that a probability or error rate lies strictly inside (0, 1)."""
        # Endpoints 0 and 1 have infinite z-scores or zero variance, so reject <= 0 and >= 1
        if not 0.0 < value < 1.0:
            raise ValueError(f"{name} must be strictly between 0 and 1, got {value}")
    
    
    def z_score(prob: float) -> float:
        """Standard normal quantile: the z with P(Z <= z) = prob, for 0 < prob < 1."""
        _check_probability("prob", prob)
        # NormalDist() defaults to mean=0, std=1; inv_cdf maps cumulative area -> z-score
        return NormalDist().inv_cdf(prob)
    
    
    def sample_size_per_group(baseline: float, relative_mde: float,
                              alpha: float = 0.05, power: float = 0.80) -> int:
        """Users needed in EACH group of a two-sided two-proportion z-test."""
        # Phase 1: Validate inputs before touching quantiles or division by delta^2
        if relative_mde == 0.0:
            raise ValueError("relative_mde must be non-zero")
    
        control_rate = baseline
        variant_rate = baseline * (1.0 + relative_mde)
        _check_probability("baseline", control_rate)
        _check_probability("variant rate", variant_rate)
        _check_probability("alpha", alpha)
        _check_probability("power", power)
    
        # Phase 2: Sum critical z-scores for two-sided alpha (alpha/2 in each tail) and target power
        z_alpha_two_sided = z_score(1.0 - alpha / 2.0)
        z_power = z_score(power)
        z_sum = z_alpha_two_sided + z_power
    
        # Phase 3: Compute two-group Bernoulli variance under the pooled probability p = (p1 + p2) / 2
        pooled_rate = (control_rate + variant_rate) / 2.0
        variance_per_user = pooled_rate * (1.0 - pooled_rate)
        two_group_variance = 2.0 * variance_per_user
    
        # Phase 4: Solve delta = z_sum * sqrt(two_group_variance / n) for n and round UP to a whole user
        effect_size = variant_rate - control_rate
        raw_sample_size = (z_sum ** 2) * two_group_variance / (effect_size ** 2)
        # Always use math.ceil (never round/int) so the test is never left slightly underpowered
        return math.ceil(raw_sample_size)
    
  4. Trace Example 1 step by step

    Substitute Example 1 (baseline = 0.08, relative_mde = 0.125, alpha = 0.05, power = 0.80) into every line:

    1. Rates & effect:   control_rate = 0.0800, variant_rate = 0.0900, effect_size = 0.0100
    2. Pooled variance:  pooled_rate = (0.0800 + 0.0900) / 2 = 0.0850
                         two_group_variance = 2 * 0.0850 * 0.9150 = 0.15555
    3. Noise-to-signal:  0.15555 / (0.0100)^2 = 0.15555 / 0.0001 = 1,555.5
    4. Z-score multiplier: z(0.975) = 1.959964, z(0.80) = 0.841621
                         z_sum = 2.801585  ->  z_sum^2 = 7.848880
    5. Sample size:      raw_sample_size = 7.848880 * 1,555.5 = 12,208.93
                         math.ceil(12,208.93) = 12,209 users PER ARM (24,418 users total)
    

    At a whiteboard without a calculator, the mental-math approximation z_sum ≈ 1.96 + 0.84 = 2.80 (2.80^2 = 7.84) gives 7.84 * 1,555.5 = 12,195.1 -> 12,196 users per arm—within 0.11% of the exact normal quantile result.

  5. Convert per-group sample size into whole experiment days

    A classic interview mistake is dividing 12,209 directly by 6,000 daily shoppers (3 days)—forgetting that Control and Variant share that daily inflow (3,000 shoppers per arm per day), so across n_groups equal arms we must collect total_users_needed = n_per_group * n_groups shoppers overall!

    Watch out for a floating-point precision trap as well. When n_groups = 3, daily_users = 13,000, and n_per_group = 65,000, total users needed is 3 * 65,000 = 195,000 = 15 * 13,000—an exact 15 days. Yet in IEEE-754 floating point, 65_000 / (13_000 / 3) evaluates to 15.000000000000002, causing math.ceil to return 16! Exact integer ceiling division (total_users_needed + daily_users - 1) // daily_users avoids floating-point error altogether:

    def experiment_days(n_per_group: int, daily_users: int, n_groups: int = 2) -> int:
        """Whole days until every group has n_per_group users, with traffic split evenly across n_groups."""
        if n_per_group < 0:
            raise ValueError("n_per_group must be non-negative")
        if daily_users <= 0 or n_groups <= 0:
            raise ValueError("daily_users and n_groups must be positive")
    
        # Total users across all arms must be collected at rate `daily_users` per day
        total_users_needed = n_per_group * n_groups
    
        # Use exact integer ceiling division (a + b - 1) // b instead of float ceil(n / (daily / groups))
        # so repeating fractions like 13,000 / 3 never add a phantom extra day at exact multiples
        return (total_users_needed + daily_users - 1) // daily_users
    
    Example 1:  2 * 12,209 = 24,418 total shoppers  ->  24,418 / 6,000 = 4.07 days  ->  5 whole days
    Example 3:  3 * 15,000 = 45,000 total shoppers  ->  45,000 / 9,000 = 5.00 days  ->  5 whole days
    

    Practical scheduling note: Even though 5 days reaches 12,209 shoppers per arm, online shopping behavior differs sharply between weekday commute browsing and Sunday evening checkout peaks. Pre-committing to 7 full days (one complete weekly cycle) balances every day of the week evenly and lifts statistical power for a +12.5% relative effect to ~96% (21,000 shoppers per arm).

  6. Why shrinking the MDE explodes the required duration

    Notice where effect_size appears in the formula: n scales proportional to 1 / delta^2. Because delta is squared in the denominator, cutting the Minimum Detectable Effect in half divides delta^2 by 4—requiring nearly 4 times as many shoppers and 4 times as many days (Example 2):

    Relative MDE   Target rate   Absolute delta   Users per arm   Days at 6,000/day
    -------------------------------------------------------------------------------
       +25.00%        10.00%        +2.00 pp            3,215              2 days
       +12.50%         9.00%        +1.00 pp           12,209              5 days  (Example 1)
        +6.25%         8.50%        +0.50 pp           47,529             16 days  (Example 2, ~3.89x users)
        +2.50%         8.20%        +0.20 pp          292,132             98 days  (~23.9x users)
        +1.25%         8.10%        +0.10 pp        1,161,945            388 days  (~95.2x users)
    

    (47,529 / 12,209 = 3.89, just below 4.00, because 8.25% has slightly smaller Bernoulli variance p*(1-p) than 8.50%.) When catching a tiny +1% or +2% lift would stall product iteration for months, teams broaden traffic eligibility, apply CUPED (Controlled-experiment Using Pre-Experiment Data—a variance-reduction technique that adjusts out each user's pre-experiment purchase propensity), or align on a larger practical MDE.

  7. Complete Python solution

    Combining z_score, sample_size_per_group, experiment_days, and plan_experiment completes the module:

    from typing import Tuple
    import math
    from statistics import NormalDist
    
    
    def _check_probability(name: str, value: float) -> None:
        """Validate that a probability or error rate lies strictly inside (0, 1)."""
        # Endpoints 0 and 1 have infinite z-scores or zero variance, so reject <= 0 and >= 1
        if not 0.0 < value < 1.0:
            raise ValueError(f"{name} must be strictly between 0 and 1, got {value}")
    
    
    def z_score(prob: float) -> float:
        """Standard normal quantile: the z with P(Z <= z) = prob, for 0 < prob < 1."""
        _check_probability("prob", prob)
        # NormalDist() defaults to mean=0, std=1; inv_cdf maps cumulative area -> z-score
        return NormalDist().inv_cdf(prob)
    
    
    def sample_size_per_group(baseline: float, relative_mde: float,
                              alpha: float = 0.05, power: float = 0.80) -> int:
        """Users needed in EACH group of a two-sided two-proportion z-test.
    
        The variant rate is baseline * (1 + relative_mde). Use the pooled rate p = (p1 + p2) / 2
        for the standard deviation sqrt(p * (1 - p)) of one user, and round up to a whole user:
    
            n = (z_{1 - alpha/2} + z_{power})^2 * 2 * p * (1 - p) / (p2 - p1)^2
    
        Raises ValueError if a rate is outside (0, 1), relative_mde is 0, or alpha / power are outside (0, 1).
        """
        # Phase 1: Validate inputs before touching quantiles or division by delta^2
        if relative_mde == 0.0:
            raise ValueError("relative_mde must be non-zero")
    
        control_rate = baseline
        variant_rate = baseline * (1.0 + relative_mde)
        _check_probability("baseline", control_rate)
        _check_probability("variant rate", variant_rate)
        _check_probability("alpha", alpha)
        _check_probability("power", power)
    
        # Phase 2: Sum critical z-scores for two-sided alpha (alpha/2 in each tail) and target power
        z_alpha_two_sided = z_score(1.0 - alpha / 2.0)
        z_power = z_score(power)
        z_sum = z_alpha_two_sided + z_power
    
        # Phase 3: Compute two-group Bernoulli variance under the pooled probability p = (p1 + p2) / 2
        pooled_rate = (control_rate + variant_rate) / 2.0
        variance_per_user = pooled_rate * (1.0 - pooled_rate)
        two_group_variance = 2.0 * variance_per_user
    
        # Phase 4: Solve delta = z_sum * sqrt(two_group_variance / n) for n and round UP to a whole user
        effect_size = variant_rate - control_rate
        raw_sample_size = (z_sum ** 2) * two_group_variance / (effect_size ** 2)
        # Always use math.ceil (never round/int) so the test is never left slightly underpowered
        return math.ceil(raw_sample_size)
    
    
    def experiment_days(n_per_group: int, daily_users: int, n_groups: int = 2) -> int:
        """Whole days until every group has n_per_group users, with traffic split evenly across n_groups.
    
        Raises ValueError if daily_users or n_groups is not positive.
        """
        if n_per_group < 0:
            raise ValueError("n_per_group must be non-negative")
        if daily_users <= 0 or n_groups <= 0:
            raise ValueError("daily_users and n_groups must be positive")
    
        # Total users across all arms must be collected at rate `daily_users` per day
        total_users_needed = n_per_group * n_groups
    
        # Use exact integer ceiling division (a + b - 1) // b instead of float ceil(n / (daily / groups))
        # so repeating fractions like 13,000 / 3 never add a phantom extra day at exact multiples
        return (total_users_needed + daily_users - 1) // daily_users
    
    
    def plan_experiment(baseline: float, relative_mde: float, daily_users: int,
                        alpha: float = 0.05, power: float = 0.80) -> Tuple[int, int]:
        """(users per group, days) for a 50/50 test."""
        # Compute per-group sample size first, then translate 2 equal arms into whole days
        users_per_group = sample_size_per_group(baseline, relative_mde, alpha, power)
        days_needed = experiment_days(users_per_group, daily_users, n_groups=2)
        return users_per_group, days_needed
    
    
    if __name__ == "__main__":
        print(plan_experiment(0.08, 0.125, 6_000))  # (12209, 5)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of power analysis like deciding how many times you must flip two coins to prove one lands heads 9.0% of the time instead of 8.0%. Across just 100 flips per coin, ordinary luck swings heads by 2%–3%, completely burying a 1.0 percentage-point edge. As you collect n shoppers per arm, sampling noise shrinks proportional to 1 / sqrt(n)—until the bell curve for "no real change" and the bell curve for "true +1.0 point lift" pull far enough apart that you rarely trigger false alarms and rarely miss a genuine improvement.

Without sizing the test up front, teams stumble in three predictable ways: stopping after "a thousand shoppers" with under 20% statistical power, confusing a +12.5% relative lift (8.0% -> 9.0%) with a +12.5 percentage-point jump (8.0% -> 20.5%, under-sizing n by nearly 100x!), or dividing one arm's sample requirement by combined daily site traffic instead of per-arm traffic.

Walking through Example 1 ("Express Checkout" button) step by step: 1. Effect size (delta): Baseline p1 = 0.080 with a +12.5% relative Minimum Detectable Effect (MDE)—the smallest true lift the experiment is sized to catch reliably—gives p2 = 0.090, an absolute difference of delta = 0.010. 2. Per-shopper variance: Using pooled rate p = (0.080 + 0.090) / 2 = 0.085, two-arm Bernoulli variance is 2 * 0.085 * (1 - 0.085) = 0.15555. 3. Critical z-score sum: Two-sided significance level alpha = 0.05 (max 5% false-positive rate, 2.5% in each tail) requires z(0.975) = 1.960, and statistical power 0.80 (80% probability of detecting delta) requires z(0.80) = 0.842, summing to 2.8016 (2.8016^2 = 7.8489). 4. Users and days: n = 7.8489 * 0.15555 / 0.010^2 = 12,208.93, rounding up to 12,209 shoppers per arm (24,418 across both arms). At 6,000 eligible shoppers/day (3,000 per arm), ceil(24,418 / 6,000) = 5 mathematical days—and because delta is squared in the denominator, halving the MDE to +6.25% relative (Example 2) roughly quadruples the sample to 47,529 per arm (16 days).

Complexity

  • Time complexity: O(1). Evaluating NormalDist().inv_cdf twice runs a fixed-degree rational polynomial approximation, followed by a constant number of arithmetic operations and a single integer division regardless of how large daily_users or n_per_group is.
  • Space complexity: O(1). Only a handful of scalar floating-point and integer variables are stored in memory; we never allocate per-user arrays or simulate individual shoppers inside the calculator.

Edge cases

  • Zero MDE (relative_mde == 0): Distinguishing two identical conversion rates (delta = 0) requires infinitely many users and divides by zero, so sample_size_per_group raises ValueError.
  • Probabilities outside (0, 1): Even when baseline = 0.92 is valid on its own, a +12.5% relative lift pushes variant_rate to 1.035 (> 1), which is impossible for a conversion rate and must raise ValueError. Also, when n * p is very small (fewer than ~5–10 expected conversions per arm), the normal approximation loses accuracy and Fisher's exact test or binomial simulation should be used instead.
  • Negative MDE (guarding against a drop): A -12.5% relative drop (8.0% -> 7.0%) pools at p = 0.075, where p * (1 - p) is slightly smaller than at 0.085—requiring 10,891 shoppers per arm instead of 12,209.
  • Exact multiples and repeating fractions in day scheduling: 15,000 per arm across 3 arms at 9,000/day takes 5 exact days (Example 3), while 12,001 across 2 arms at 6,000/day takes 5 days (24,002 / 6,000). Computing (n_per_group * n_groups + daily_users - 1) // daily_users in pure integers avoids floating-point drift when daily_users / n_groups is a repeating fraction (such as 13,000 / 3, where 65,000 / (13,000 / 3) becomes 15.000000000000002 and float ceil wrongly returns 16 instead of 15).
  • Zero users needed (n_per_group == 0): Integer ceiling division (0 + daily_users - 1) // daily_users returns 0 days cleanly, while negative n_per_group raises ValueError.

Common mistakes

  • Using a one-sided z-score (z(0.95) = 1.645) for a two-sided test: Substituting 1.645 instead of 1.960 shrinks (z_alpha + z_power)^2 from 7.85 to 6.18, returning 9,617 shoppers/arm—under-sizing the test by 21%.
  • Confusing relative MDE (+12.5% of 8% = +1.0 pp) with absolute MDE (+12.5 pp): Setting p2 = 0.205 instead of 0.090 inflates delta by 12.5x and suggests just 123 shoppers per arm!
  • Dividing one arm's sample size by combined two-arm traffic: Computing ceil(12,209 / 6,000) = 3 days forgets that only half of daily shoppers (3,000/day) enter each arm.
  • Rounding n or days to nearest instead of ceiling: round(4.07) = 4 days (24,000 total shoppers) stops short of 24,418 and leaves true power below 80%.
  • Peeking daily and halting at the first p < 0.05: Checking a fixed-horizon z-test every morning and stopping early on random luck inflates false positives well past 5%; fix the duration up front or use a sequential test (an always-valid boundary widened to permit continuous monitoring).
  • Randomizing shoppers while treating repeat pageviews as independent trials: If one shopper views 6 product pages, those 6 views are correlated; variance must be computed at the randomization unit (the shopper), using the delta method if evaluating pageview-level ratio metrics.

Alternative approaches

  • Unpooled alternative variance: Using p1 * (1 - p1) + p2 * (1 - p2) = 0.1555 in place of 2 * p * (1 - p) = 0.15555 yields 12,206 shoppers per arm—differing by only 3 users from the pooled formula.
  • Monte Carlo power simulation: Draw Binomial(n, p1) and Binomial(n, p2) counts in NumPy and binary-search n until the empirical rejection rate hits 80%. Simulation runs in milliseconds and generalizes naturally to skewed cart-value metrics where closed-form normal formulas need extra care.
  • Variance reduction (CUPED): Regressing out each shopper's pre-experiment conversion rate reduces residual variance without requiring extra traffic, shrinking n directly.

Follow-up questions

  • What happens to the required per-arm sample size when target statistical power rises from 80% to 90%? Only z_power changes, climbing from z(0.80) = 0.8416 to z(0.90) = 1.2816, which scales (z_{0.975} + z_power)^2 from (1.9600 + 0.8416)^2 = 7.849 to (1.9600 + 1.2816)^2 = 10.507—a 1.339x (+33.9%) increase for any baseline and MDE. On Example 1 (8.0% -> 9.0%), per-arm sample size grows from 12,209 to 16,345 shoppers (32,690 total), extending the raw minimum runtime at 6,000 shoppers/day from 5 days to 6 days (32,690 / 6,000 = 5.45 days, or 7 days once rounded up to a full weekly cycle).
  • Suppose a routing defect sends an unintended 20% slice of traffic into the treatment arm—how does that assignment skew affect your test validity and conclusions? You must pause and diagnose how the skew occurred before trusting any conversion readout. If a bucketing bug diverted 20% of intended Control shoppers into Treatment (turning a 50/50 split into 40/60), a Sample Ratio Mismatch (SRM) check—a chi-square goodness-of-fit test comparing observed vs. expected arm counts—will immediately trigger (chi^2 ≈ 977, p ≈ 0); because routing defects almost always correlate with device type, browser, or login state, the arms suffer from selection bias, invalidating the p-value and requiring a bug fix plus a fresh restart. Conversely, if randomization stayed cleanly 50/50 at random while 20% of Treatment shoppers failed to render the new button (seeing Control instead), intent-to-treat dilution shrinks a +1.00 pp true lift to 0.80 * 1.00 = +0.80 pp, requiring ~1 / 0.80^2 = 1.56x as many shoppers (~18,950 per arm) to preserve 80% power.
  • Apart from hitting the target user count, what calendar or behavioral effects could require running the test longer than the raw day formula suggests? Even though 24,418 shoppers arrive in 5 days, retail conversion swings noticeably between weekday lunchtime browsing and weekend checkout sessions, so experiments should run in full 7-day multiples (at least 1–2 complete weeks) to weight every day of the week in natural proportion. Beyond day-of-week seasonality, you may need extra runtime to outlast novelty and primacy effects (curiosity clicks on an unfamiliar button in week 1, or loyal shoppers briefly hesitating on a changed layout), repeat-visitor overlap (when 6,000 daily active visitors include returning shoppers already bucketed earlier rather than 6,000 brand-new unique users), phased safety ramps (10% -> 50% traffic rollouts), and atypical holiday or flash-sale weeks whose buying behavior does not carry over to ordinary weeks.

Follow-up questions

Similar questions

More Yelp interview questions

All 5 Yelp questions →