Statistical Inference and Hypothesis Testing Questions
Reasoning about uncertainty in data and drawing formal conclusions from samples. Covers probability rules and common distributions, the Central Limit Theorem, sampling, standard error, confidence intervals, and Bayesian reasoning, together with the significance-testing framework: null and alternative hypotheses, p-values, statistical power, Type I and Type II errors, effect sizes, and choosing the right test (t-test, chi-square, non-parametric). Emphasizes correctly interpreting statistical results and avoiding common misreadings of significance in business and product contexts rather than memorizing formulas.
Given sample revenue per user values [50, 55, 60, 5000], describe two statistical methods to detect outliers and apply them to flag which values are outliers using the IQR rule and a Z-score threshold of 3. Explain how flagged outliers would affect mean and median reporting and one remediation strategy.
Sample Answer
On the sample [50, 55, 60, 5000], neither the IQR rule (1.5 times IQR beyond Q1/Q3) nor a Z-score threshold of 3 actually flags 5000 as an outlier, which is a useful lesson on its own: both rules can miss an obvious outlier when the sample is this small, because a single extreme value distorts the very statistics (IQR, mean, standard deviation) used to detect it. The bigger practical point is that the mean (1291.25) is not a trustworthy summary of this data, while the median (57.5) is.
Structured elaboration
Method 1: IQR rule
Sort the data, split into halves, and take the median of each half as Q1 and Q3:
IQR=Q3−Q1
outlier if x<Q1−1.5IQR or x>Q3+1.5IQR
Method 2: Z-score
z=sx−xˉ
flag any point with the absolute value of z at least 3 (using the sample or population standard deviation; both are shown below, and they agree on the conclusion here).
Worked example
Data sorted: [50, 55, 60, 5000].
IQR rule:
- Q1 = median(50, 55) = 52.5
- Q3 = median(60, 5000) = 2530
- IQR = 2530 - 52.5 = 2477.5
- Bounds: [52.5 - 1.5(2477.5), 2530 + 1.5(2477.5)] = [-3663.75, 6246.25]
- 5000 is inside [-3663.75, 6246.25], so the IQR rule does not flag it.
Z-score rule:
- Mean = (50+55+60+5000)/4 = 1291.25
- Population standard deviation is about 2141.25 (sample standard deviation is about 2472.50)
- z(5000) = (5000 - 1291.25) / 2141.25, which is about 1.73 with the population standard deviation, or about 1.50 with the sample standard deviation
- Neither exceeds the threshold of 3, so the Z-score rule with threshold 3 also does not flag it.
(all values verified with python3's statistics module: mean 1291.25, population standard deviation 2141.25, sample standard deviation 2472.50, z(5000) with population standard deviation is 1.732)
Both rules fail here because n = 4 is far too small for either method's underlying assumptions. Q3 itself is contaminated by the outlier since it is the median of {60, 5000}, and the mean and standard deviation are both dragged upward by the same point that inflates them, making the z-score understate its own extremity.
Impact on mean vs median, and remediation
- Mean (1291.25) is wildly unrepresentative: it is more than 20 times any of the other three values.
- Median (57.5) reflects the typical value well and is unaffected by 5000's magnitude, only its rank.
- Remediation: investigate 5000 first (a data entry error versus a genuinely high-value customer). If it is legitimate but unrepresentative for a "typical revenue per user" metric, report the median or a trimmed mean alongside the full mean, or winsorize (cap) extreme values above a chosen percentile, and call out large accounts separately rather than letting them silently dominate an average.
Trade-offs & pitfalls
- Both rules are much less reliable at small n; with only 4 points, one extreme value can shift Q3 or the standard deviation enough to mask itself. Neither rule "failing" here means the value is not actually anomalous. It means the tools were not built for n = 4.
- The IQR rule is robust to the outlier's magnitude (it depends on ranks) but not to a small sample where the quartiles themselves are computed from very few points.
- The Z-score rule is directly vulnerable to the outlier: the outlier itself inflates the standard deviation used to judge it, which can hide even large true outliers (masking).
- Silently dropping a flagged, or even an unflagged but suspicious, value without investigating whether it is a data error or a real, important case risks deleting real signal (a legitimate enterprise customer) rather than noise.
You plan a two-sided A/B test comparing conversion proportions. Baseline p0 = 0.05 and you expect a 20% relative uplift (p1 = 0.06). Using alpha=0.05 and desired power 0.8, compute the required sample size per group. Show the formula you use, numeric steps, and discuss how the calculation changes for unequal allocation or continuous metrics.
Sample Answer
Direct answer
For a two-sided test comparing two proportions with baseline p0=0.05, target p1=0.06 (20% relative lift), α=0.05, and power =0.80, the required sample size is about 8,158 per arm, computed from the standard normal-approximation formula for a two-proportion test. Unequal allocation and continuous metrics use the same underlying logic (compare the standardized difference against critical values from the desired error rates) but change the variance term and, for unequal group sizes, the optimal split between arms.
Structured elaboration
Formula (equal allocation, two-sided)
nper group=(p1−p0)2[z1−α/22pˉ(1−pˉ)+z1−βp0(1−p0)+p1(1−p1)]2where pˉ=(p0+p1)/2, z1−α/2=1.9600 for α=0.05, and z1−β=0.8416 for power =0.80.
Numeric steps
p0=0.05, p1=0.06, Δ=0.01, pˉ=0.055 2pˉ(1−pˉ)=2(0.055)(0.945)=0.32241 p0(1−p0)+p1(1−p1)=0.0475+0.0564=0.32234 numerator=1.95996(0.32241)+0.84162(0.32234)=0.90320 n=0.0120.903202=0.00010.81577=8,158(all steps reproduce exactly with plain arithmetic; verified with python3)
So you need about 8,158 users per arm, 16,320 total.
Unequal allocation
With allocation ratio r=n1/n0 (treatment vs. control), the sample size for the control arm becomes:
n0=Δ2[z1−α/2pˉ(1−pˉ)(1+1/r)+z1−βp0(1−p0)+p1(1−p1)/r]2,n1=r⋅n0with pˉ=(p0+rp1)/(1+r). The allocation ratio that minimizes the total sample size n0+n1 for a fixed variance target (Neyman allocation) is:
r∗=p0(1−p0)p1(1−p1)For this example, p0(1−p0)=0.0475 and p1(1−p1)=0.0564, so r∗=0.0564/0.0475=1.090, close to 1: with proportions this close together, equal allocation is already near-optimal, and there's little total-sample-size benefit to skewing the split. Unequal allocation becomes worth doing when one arm is deliberately capped (e.g. a risky treatment held to 10% of traffic); the cost is a larger total sample size than the balanced design would need for the same power.
Continuous metrics
Replace the proportion-variance terms with the outcome variance σ2 (estimated from historical data or a pilot):
nper group=Δ22(z1−α/2+z1−β)2σ2where Δ is the absolute mean difference you want to detect. Use a pooled or historical estimate of σ, and consider winsorizing or a log transform first if the metric is heavy-tailed, since σ2 from raw heavy-tailed data can be dominated by a handful of extreme values and understate how many "typical" observations you'll actually need.
Trade-offs & pitfalls
- For small p0 or small Δ, the normal approximation underlying this formula can be inaccurate; check that np0 and n(1−p0) are both comfortably above about 5-10, or fall back to an exact binomial/simulation-based power calculation.
- The unequal-allocation Neyman ratio only minimizes total sample size; it does not account for a fixed traffic budget per arm or for practical constraints like a hard cap on treatment exposure, so it should be treated as a starting point, not an automatic answer.
- Continuous-metric sample sizes are only as good as the variance estimate feeding them; an outdated or unrepresentative σ estimate (from before a product change, or from a different user segment) will make the planned sample size wrong in either direction.
- None of these formulas account for multiple comparisons, expected attrition, or metric seasonality; pad the computed n for real-world dropout and plan the run to cover at least one full weekly cycle regardless of what the raw sample-size number implies about duration.
Explain Simpson's paradox and provide a concrete A/B testing example with hypothetical numbers where aggregating across segments yields the opposite conclusion from segment-level analysis. Describe how you would detect such paradoxes and resolve the correct interpretation for product decisions.
Sample Answer
Direct answer
Simpson's paradox is when a trend that appears in an aggregated dataset reverses, or disappears, once the data is broken into meaningful subgroups. It happens when a subgroup variable is both correlated with the outcome and unevenly distributed across the groups being compared, so the aggregate is really comparing different mixes of subgroups rather than like-for-like. In A/B testing this can flip an experiment's headline verdict if traffic composition differs between arms.
Structured elaboration
Mechanism. The paradox needs two ingredients: a segment (e.g. new vs returning users) whose baseline conversion rate differs a lot, and a segment mix that differs between the two experiment arms, whether from a randomization bug, non-random routing, or the arms genuinely attracting different user mixes (for example, if the treatment changes something only new users see first). When the high-baseline segment is overrepresented in one arm, that arm's aggregate gets pulled up regardless of the true within-segment treatment effect.
Two distinct causes worth separating. (1) A randomization or logging bug that skews segment composition between arms even though the metric itself has a uniform effect. This should be treated like Sample Ratio Mismatch: a data-quality problem to fix, not a real result to interpret. (2) A genuine, real segment-mix or heterogeneous-effect situation (e.g. the arms were deliberately targeted differently, or the treatment interacts with user tenure). This is a real result that needs segment-aware reporting, not a bug.
Worked example
Two segments with very different baseline conversion, and arms that got very different mixes of each:
| Segment | Control | Treatment |
|---|---|---|
| High-intent users | 380 / 900 = 42.2% | 45 / 100 = 45.0% |
| Low-intent users | 6 / 100 = 6.0% | 63 / 900 = 7.0% |
| Aggregate | 386 / 1,000 = 38.6% | 108 / 1,000 = 10.8% |
(All counts verified by direct computation.) Notice: treatment wins in both segments individually (45.0% > 42.2%, and 7.0% > 6.0%), but because control's traffic was mostly high-intent users (who convert well regardless of arm) and treatment's traffic was mostly low-intent users (who convert poorly regardless of arm), the aggregate makes it look like control is dramatically better. Reading only the aggregate row would lead to killing a feature that actually helped every segment it touched.
Detection. Treat segment-mix balance as a standard experiment health check alongside SRM: compare the proportion of each key segment (device, new/returning, geography) between arms, and flag if that mix itself differs significantly between arms (a chi-square test of segment distribution by arm is a direct way to check this). Separately, fit the metric with an interaction term, metric∼arm+segment+arm:segment, to see whether the treatment effect actually differs by segment (heterogeneity) as opposed to just the segment mix differing (composition).
Resolution. If the segment-mix imbalance traces back to a bug (bad routing, non-random assignment), that invalidates the experiment; the fix is to correct randomization and rerun, not to reweight around the bug. If the imbalance is real and expected (e.g. the two arms intentionally target different populations, or a feature launch changes what fraction of traffic is new users), report segment-level effects explicitly rather than a single aggregate number, and if a single summary number is still needed, use a standardized/weighted average that applies one fixed reference mix (e.g. last month's traffic composition) to both arms instead of letting each arm's own live mix drive the number.
Trade-offs & pitfalls
- Don't go looking for a favorable segment cut after seeing an unfavorable aggregate result; that's post-hoc fishing and needs the same multiple-comparisons discipline as any other exploratory subgroup analysis. Segment checks belong in the pre-registered analysis plan, run regardless of which way the aggregate goes.
- Trusting an aggregate number without ever looking at segment balance is the classic wrong turn, and it's especially dangerous because the aggregate looks perfectly clean (large N, tight CI) even while hiding a completely reversed within-segment story.
- Not every segment-level difference is Simpson's paradox; if segment mix is balanced across arms and the aggregate and segment-level conclusions agree, that's just a normal heterogeneous-effect finding, worth reporting, but not a paradox to resolve.
In a linear regression model predicting revenue per user, explain the difference between a confidence interval for the mean response at a particular x* and a prediction interval for a new observation at x*. Provide formulas (assuming homoscedastic Gaussian errors) and describe how interval widths change with sample size and residual variance.
Sample Answer
Direct answer
A confidence interval at x∗ captures uncertainty about the average outcome for that x value (a population quantity); a prediction interval at x∗ captures uncertainty about one new individual observation at that x value. The prediction interval is always wider because it has to account for both the uncertainty in estimating the regression line and the irreducible noise around that line, while the confidence interval only accounts for the first source.
Structured elaboration
Setup. Simple linear regression y=β0+β1x+ε, ε∼N(0,σ2) i.i.d. (homoscedastic Gaussian errors). Let y^(x∗)=β^0+β^1x∗, s2=RSS/(n−2), and Sxx=∑i(xi−xˉ)2.
Confidence interval for the mean response E[y∣x∗]:
y^(x∗)±tn−2,α/2sn1+Sxx(x∗−xˉ)2This only reflects how precisely you've pinned down the regression line itself, since E[y∣x∗] is a fixed number, not a random draw.
Prediction interval for a new observation ynew at x∗:
y^(x∗)±tn−2,α/2s1+n1+Sxx(x∗−xˉ)2The extra "1" inside the square root is exactly σ2 worth of individual-observation noise that a single future draw carries and that never goes away, regardless of how much data you have.
How the widths change:
| Factor | Confidence interval | Prediction interval |
|---|---|---|
| Sample size n→∞ | Width →0 | Width → a floor set by 2zα/2σ (never zero) |
| Residual variance s2 up | Wider (linear in s) | Wider, and dominates once 1≫1/n |
| x∗ far from xˉ | Wider (via (x∗−xˉ)2/Sxx) | Wider, but the effect is proportionally smaller since the "1" term dominates |
The practical takeaway: growing the sample only tightens the CI meaningfully; it barely tightens the PI, because the PI's floor is set by σ itself, not by how well you know β0,β1.
Worked example
Simulated revenue-per-user regression (pinned seed, n=40):
import numpy as np
from scipy import stats
rng = np.random.default_rng(7)
n = 40
x = rng.uniform(1, 10, n)
y = 5.0 + 3.0 * x + rng.normal(0, 4.0, n) # true b0=5, b1=3, sigma=4
xbar, Sxx = x.mean(), np.sum((x - x.mean())**2)
b1 = np.sum((x - xbar) * (y - y.mean())) / Sxx
b0 = y.mean() - b1 * xbar
resid = y - (b0 + b1 * x)
s = np.sqrt(np.sum(resid**2) / (n - 2))
xstar = 8.0
yhat = b0 + b1 * xstar
tcrit = stats.t.ppf(0.975, n - 2)
se_mean = s * np.sqrt(1/n + (xstar - xbar)**2 / Sxx)
se_pred = s * np.sqrt(1 + 1/n + (xstar - xbar)**2 / Sxx)
print(f"fitted: b0={b0:.3f}, b1={b1:.3f}, s={s:.3f} (xbar={xbar:.3f}, Sxx={Sxx:.2f})")
print(f"yhat(x*=8.0) = {yhat:.3f}, t_crit(df={n-2}, .975) = {tcrit:.3f}")
print(f"95% CI for mean response: [{yhat-tcrit*se_mean:.3f}, {yhat+tcrit*se_mean:.3f}] half-width = {tcrit*se_mean:.3f}")
print(f"95% PI for new observation: [{yhat-tcrit*se_pred:.3f}, {yhat+tcrit*se_pred:.3f}] half-width = {tcrit*se_pred:.3f}")
Output:
fitted: b0=2.027, b1=3.569, s=3.218 (xbar=5.238, Sxx=282.42)
yhat(x*=8.0) = 30.577, t_crit(df=38, .975) = 2.024
95% CI for mean response: [29.091, 32.063] half-width = 1.486
95% PI for new observation: [23.895, 37.259] half-width = 6.682
The prediction interval is about 4.5 times wider than the confidence interval at the same x∗, entirely because of the extra "1" term, since both intervals use the same y^(x∗), s, tn−2, n, and (x∗−xˉ)2/Sxx.
Trade-offs & pitfalls
The most common mistake in practice is reporting a confidence interval when the actual question is about a single future user (e.g. "what revenue should we expect from a new customer with these attributes") - that calls for a prediction interval, and using the CI there systematically understates risk. The reverse mistake, reporting a PI when summarizing the average effect across a segment, needlessly widens the story and can make a real, precisely-estimated average look uncertain. Both formulas also assume homoscedastic Gaussian errors; if the residual spread grows with x (heteroscedasticity) or is skewed, these closed-form intervals are wrong in both center and width, and a weighted-least-squares model or a bootstrap-based interval that estimates residual spread locally is the more defensible choice.
State the Central Limit Theorem (CLT) precisely for IID random variables with finite variance. Explain its implications for sample means and sampling distributions in practice. Give a recommended rule-of-thumb for when the CLT can be used, and sketch a short simulation plan (pseudocode) that demonstrates CLT convergence for a highly skewed distribution.
Sample Answer
For independent, identically distributed random variables with finite variance, the Central Limit Theorem says the (properly scaled) sample mean converges in distribution to a normal distribution as the sample size grows, regardless of the shape of the original distribution. In practice this means confidence intervals and z/t-based tests built on a sample mean are approximately valid once n is "large enough," even when the underlying data itself is skewed or non-normal.
Structured elaboration
Precise statement
Let X1, X2, ..., Xn be IID with mean mu and finite variance sigma^2 less than infinity. Let X_bar_n be the sample mean. Then as n approaches infinity:
n(Xˉn−μ)dN(0,σ2)
Equivalently, for large n:
Xˉn≈N(μ,nσ2)
so the standard error of the mean is sigma divided by the square root of n, shrinking as n grows regardless of the shape of the original distribution X.
Implications for practice
- The sampling distribution of a mean becomes approximately bell-shaped even when individual observations are heavily skewed (latency, revenue, task time).
- This is what licenses z-intervals, t-tests, and z-tests on averages and proportions, even for non-normal raw data.
- Convergence is not instantaneous or uniform: the more skewed or heavy-tailed the underlying distribution, the larger n needs to be before the normal approximation is trustworthy.
Rule of thumb
- Roughly symmetric, light-tailed data: n of 30 or more is often enough.
- Noticeably skewed data: n of 50 to 100.
- Heavy-tailed or extremely skewed data (or when tail behavior itself matters): treat the CLT-based interval with caution regardless of n, and prefer bootstrap or robust methods.
Worked example
Simulate the sampling distribution of the mean of an Exponential(1) distribution (population skewness = 2, a strongly right-skewed case) for growing n, and track how quickly its skewness and standard error approach the CLT prediction:
import random, math
random.seed(11)
def sample_exp(rate=1.0):
u = random.random()
return -math.log(1 - u) / rate
def skewness(xs):
n = len(xs)
m = sum(xs) / n
m2 = sum((x - m) ** 2 for x in xs) / n
m3 = sum((x - m) ** 3 for x in xs) / n
return m3 / (m2 ** 1.5)
R = 5000
for n in [5, 10, 30, 100, 500]:
means = [sum(sample_exp() for _ in range(n)) / n for _ in range(R)]
mean_of_means = sum(means) / R
sd_of_means = math.sqrt(sum((x - mean_of_means) ** 2 for x in means) / R)
print(n, sd_of_means, skewness(means))
Running this (seed 11, R = 5,000 replicates per n) gives:
| n | empirical SE of the mean | theory: sigma / sqrt(n) | empirical skewness of the means | theory: 2 / sqrt(n) |
|---|---|---|---|---|
| 5 | 0.450 | 0.447 | 0.889 | 0.894 |
| 10 | 0.320 | 0.316 | 0.602 | 0.632 |
| 30 | 0.185 | 0.183 | 0.323 | 0.365 |
| 100 | 0.099 | 0.100 | 0.237 | 0.200 |
| 500 | 0.044 | 0.045 | 0.109 | 0.089 |
Both the standard error and the skewness of the sample-mean distribution shrink toward the CLT prediction as n grows, even starting from a distribution with skewness 2. By n = 500 the skewness of the sampling distribution of the mean (about 0.11) is far closer to a normal distribution's skewness of 0 than the original Exponential's skewness of 2.
Trade-offs & pitfalls
- The CLT describes the sampling distribution of the mean, not the distribution of individual observations; individual data points from a skewed distribution stay skewed no matter how large n gets.
- "n of 30 or more" is a rough convention, not a law; a heavily skewed or heavy-tailed distribution (or ratio metrics, or rare-event counts) can need a much larger n before the normal approximation is trustworthy.
- Sums also converge under the CLT, not just means, but variance-based reasoning must use the right scaling (variance of a sum grows with n; variance of a mean shrinks with n).
- CLT-based intervals are approximate. When in doubt, especially for skewed metrics with a business-critical decision riding on the interval, a bootstrap confidence interval is a useful cross-check.
Unlock Full Question Bank
Get access to all Statistical Inference and Hypothesis Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.