Data Science Interview Questions
Data science interview track: exploratory data analysis, hypothesis testing, p-values, feature engineering, dimensional reduction (PCA), and Pandas/NumPy vectorization.
Practice Data Science Interview Questions
Showing 16 of 16 technical questions with engineering explanations
What is the exact definition of a p-value, and what are the three most common misinterpretations in interviews?
Senior Engineering Answer
A p-value is the probability of observing a test statistic at least as extreme as the one measured in your sample, assuming the null hypothesis H_0 (and all model assumptions) is true: P(data >= observed | H_0). Three classic errors: (1) thinking it is P(H_0 | data)—the probability that the null is true (which requires Bayes' theorem and a prior); (2) thinking 1 - p is the probability of replication; and (3) equating statistical significance (p < 0.05) with practical business impact—with 10 million users, a meaningless 0.01% lift yields p < 0.0001.
from scipy import stats
t_stat, p_val = stats.ttest_ind(treatment_rev, control_rev, equal_var=False)
print(f"Welch t={t_stat:.3f}, p={p_val:.4f}")Saying 'p = 0.03 means there is a 97% chance the treatment works' is an instant red flag—always state that p conditions on H_0 being true.
Explain Simpson's Paradox with a concrete product analytics example and how stratification resolves it.
Senior Engineering Answer
Simpson's Paradox happens when an aggregate trend reverses or vanishes once the dataset is stratified by a confounding variable. For example, Treatment B shows a lower overall conversion rate than Control A (14% vs 18%), yet B beats A on BOTH mobile (12% vs 10%) and desktop (26% vs 24%). This occurs when traffic allocation was imbalanced across segments (e.g., 85% of B went to low-converting mobile users while 70% of A went to high-converting desktop users). Stratifying by device—or checking randomization balance—exposes the confounder.
SELECT device_type, variant, COUNT(*) AS users, AVG(converted::float) AS conv_rate FROM exp_events GROUP BY 1, 2 ORDER BY 1, 2;
Do not blindly stratify on variables affected BY the treatment (post-treatment mediators or colliders), as conditioning on a collider induces spurious bias.
Distinguish MCAR, MAR, and MNAR missing data mechanisms, and explain why naive mean imputation distorts variance and correlations.
Senior Engineering Answer
MCAR (Missing Completely at Random) means missingness is independent of both observed and unobserved values (e.g., random sensor packet drop). MAR (Missing at Random) means missingness depends only on observed variables (e.g., younger users skip salary fields, explainable by age)—handled well by Multiple Imputation (MICE) or model-based imputation. MNAR (Missing Not at Random) means missingness depends on the unobserved value itself (e.g., sickest patients drop out of a trial), requiring explicit missingness indicators or sensitivity bounds. Replacing NAs with the column mean artificially shrinks standard errors and attenuates feature correlations toward zero.
from sklearn.impute import SimpleImputer # Preserve missingness signal via add_indicator=True; fit strictly on train! imp = SimpleImputer(strategy="median", add_indicator=True) X_train_imp = imp.fit_transform(X_train) X_val_imp = imp.transform(X_val)
Dropping missing rows blindly when data is MAR or MNAR introduces severe selection bias.
What are Type I errors, Type II errors, Statistical Power, and Minimum Detectable Effect (MDE) in A/B test sizing?
Senior Engineering Answer
Type I error (alpha, typically 0.05) is a false positive—shipping a no-op change. Type II error (beta, typically 0.20) is a false negative—missing a real win; Power = 1 - beta (typically 80%). MDE is the smallest true relative or absolute lift worth detecting from a business ROI standpoint. Required sample size per variant grows approximately as n ~ 16 * sigma^2 / delta^2 for 80% power at alpha=0.05: halving the MDE quadruples the required sample size and experiment duration.
import math
def ab_sample_size_per_group(p_baseline, mde_abs, alpha=0.05, power=0.80):
# Normal approximation for two-proportion z-test (z_alpha/2=1.96, z_beta=0.84)
z_a, z_b = 1.96, 0.8416
p2 = p_baseline + mde_abs
var = p_baseline * (1 - p_baseline) + p2 * (1 - p2)
return math.ceil(((z_a + z_b) ** 2 * var) / (mde_abs ** 2))Running underpowered tests and celebrating 'no statistically significant difference' as proof of zero harm (e.g., on a guardrail metric)—low power simply means inconclusive noise.
Why does repeated 'peeking' at A/B test p-values inflate false positives, and how do Sequential Testing (Always-Valid p-values) or Group Sequential designs solve it?
Senior Engineering Answer
Checking a fixed-horizon t-test daily and stopping the moment p < 0.05 inflates the cumulative Type I error from 5% to 20–30%+ because random walks cross significance boundaries by chance. Fix this either with (1) Group Sequential Testing using alpha-spending functions (O'Brien-Fleming spends tiny alpha early like p < 0.0005 and saves most for the final look) or (2) Always-Valid p-values / mSPRT (mixture Sequential Probability Ratio Test), which construct confidence sequences valid at every continuous stopping time with guaranteed false-positive control.
# Fixed-horizon: check ONCE at pre-registered N (or full week cycles) # Group sequential (O'Brien-Fleming): 3 planned looks -> interim p thresholds ~0.0005, 0.014, 0.045
Extending an experiment 'just a few more days because p = 0.06 looks promising' invalidates standard p-values just as much as stopping early.
How do you correct for Multiple Hypothesis Testing across 20 metrics or segments, comparing Bonferroni vs Benjamini-Hochberg (FDR)?
Senior Engineering Answer
Testing M=20 independent null hypotheses at alpha=0.05 gives 1 - 0.95^20 = 64% chance of at least one false positive. Bonferroni controls the Family-Wise Error Rate (FWER—probability of ANY false positive) by testing each hypothesis at alpha / M (0.0025), which is safe for critical safety/launch gates but severely kills power when M is large. Benjamini-Hochberg controls the False Discovery Rate (FDR—expected proportion of false positives among rejected hypotheses) by sorting p_(1) <= ... <= p_(M) and rejecting up to the largest k where p_(k) <= (k / M) * q—ideal for exploratory feature/segment discovery.
from statsmodels.stats.multitest import multipletests reject, p_adj, _, _ = multipletests(raw_p_values, alpha=0.05, method="fdr_bh")
Running post-hoc subgroup breakdowns across 15 countries and highlighting the one country with p = 0.03 without multiple-testing correction.
How do you identify and prevent feature leakage and target leakage in analytical and predictive pipelines?
Senior Engineering Answer
Leakage occurs when training features incorporate information unavailable at prediction time. Examples: fitting StandardScaler, PCA, or target encoders before the train/test split; joining mutable database tables (like current_account_tier or last_updated_at) instead of historical event snapshots; or including proxy columns recorded after the event (e.g., cancellation_reason when predicting churn). Prevent leakage by wrapping every preprocessor inside scikit-learn Pipelines, enforcing temporal train/val/test cutoffs, inspecting suspiciously perfect single-feature AUCs (>0.99), and reconstructing features strictly from event logs prior to the prediction timestamp.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([("scaler", StandardScaler()), ("clf", LogisticRegression())])Computing global aggregates like 'user_lifetime_orders' across the whole table and using it to predict whether a user converts on their second visit.
How do you analyze heavily skewed, zero-inflated metrics like revenue per user or page latency in an A/B test?
Senior Engineering Answer
Skewed revenue (95% zeros, 0.1% whales) slows Central Limit Theorem convergence, creates huge variance, and lets two whale users flip the mean. Common strategies: (1) check sample size—if n > 10k per arm, Welch's t-test or percentile/studentized bootstrap often holds well unless extreme outliers dominate; (2) cap/winsorize extreme top 0.1% outliers (using a pre-registered threshold independent of variant) to stabilize variance; (3) decompose into two business metrics (Conversion Rate P(rev > 0) and Average Order Value among payers); or (4) use Mann-Whitney U when testing stochastic dominance rather than difference in means (note: Mann-Whitney tests rank shifts, not means!).
import numpy as np cap = np.percentile(np.concatenate([ctrl, trt]), 99.9) ctrl_w = np.clip(ctrl, None, cap) trt_w = np.clip(trt, None, cap)
Log-transforming revenue (log(1 + y)) and claiming a significant difference in log-means implies a positive difference in total dollar revenue—a lower variance with the same mean can raise E[log(Y)] while lowering E[Y]!
What is CUPED (Controlled-experiment Using Pre-Experiment Data), and how does it cut A/B test sample size requirements by 30–60%?
Senior Engineering Answer
CUPED reduces variance of an outcome metric Y by subtracting a zero-mean term built from a pre-experiment covariate X (such as the user's metric value in the 14 days before randomization): Y_cuped = Y - theta * (X - E[X]), where optimal theta = Cov(Y, X) / Var(X). Because X was measured before treatment assignment, E[X_trt] == E[X_ctrl] in expectation, keeping the treatment effect unbiased while reducing variance by factor (1 - rho^2), where rho = Corr(Y, X). If pre/post spend correlates at rho = 0.7, variance drops by 49%, cutting required experiment runtime nearly in half.
import numpy as np
def apply_cuped(y, x_pre):
theta = np.cov(y, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1)
return y - theta * (x_pre - np.mean(x_pre))Computing theta separately per variant or using post-assignment covariates for X introduces bias; theta and E[X] must be estimated across the pooled sample using strictly pre-experiment data.
Why is a standard user-level t-test invalid for ratio metrics like Click-Through Rate (clicks / impressions) when randomization is by user?
Senior Engineering Answer
If you randomize by user_id, individual impressions or pageviews from the same user are positively correlated, violating the i.i.d. assumption of a binomial z-test on pooled clicks/impressions and severely underestimating standard errors (producing huge false-positive rates). Instead, compute the numerator N_i (clicks) and denominator D_i (impressions) per randomization unit (user i), and compute variance of the ratio R = sum(N_i) / sum(D_i) using the Delta Method (linearizing via Taylor expansion: Var(N/D) using Var(N), Var(D), and Cov(N, D)) or a cluster bootstrap resampling user_ids.
import numpy as np
def delta_ratio_variance(num, den):
n = len(num)
mu_n, mu_d = np.mean(num), np.mean(den)
var_n = np.var(num, ddof=1)
var_d = np.var(den, ddof=1)
cov_nd = np.cov(num, den, ddof=1)[0, 1]
return (var_n / mu_d**2 + (mu_n**2 * var_d) / mu_d**4 - (2 * mu_n * cov_nd) / mu_d**3) / nAveraging each user's personal CTR (mean(N_i / D_i)) instead of overall ratio (sum(N_i) / sum(D_i)) weights light 1-impression users equally with heavy 100-impression users, changing the estimand.
How do you estimate causal impact when you cannot run a randomized A/B test? Compare Difference-in-Differences (DiD), Propensity Score Matching, and Synthetic Control.
Senior Engineering Answer
When randomization is blocked (e.g., regional policy launch, enterprise contract opt-in), choose based on data structure and identification assumptions: (1) Propensity Score Matching/IPTW reweights treated and control units by P(T=1 | X), assuming Ignorability/Unconfoundedness (no unobserved confounders); (2) Difference-in-Differences compares pre-to-post changes between treated and control cohorts, removing time-invariant unobserved differences under the Parallel Trends assumption (verified via pre-period event-study plots); (3) Synthetic Control constructs an optimal convex-weighted combination of donor units (e.g., untreated cities) matching pre-treatment outcome trajectories when only one or few units receive treatment.
# DiD regression specification: # Y_it = beta0 + beta1*Treated_i + beta2*Post_t + beta3*(Treated_i * Post_t) + eps_it # beta3 estimates the Average Treatment Effect on the Treated (ATT)
Claiming causal proof from Propensity Score Matching without sensitivity analysis for hidden confounders, or failing to check pre-treatment parallel trends in DiD.
What causes Sample Ratio Mismatch (SRM) in online experiments, how do you detect it, and why must you never analyze results when SRM fails?
Senior Engineering Answer
SRM occurs when observed traffic counts across variants deviate significantly from the configured allocation (e.g., expecting 50/50 but observing 50.6%/49.4% over 1M users). Detect it via a Pearson Chi-Square goodness-of-fit test with a strict threshold like p < 0.001. SRM indicates broken randomization or differential telemetry loss—such as client crashes in Treatment preventing exposure logging, bot filtering differences, redirect latency drops, or sticky caching bugs. Because missing users are non-random, any downstream conversion or revenue analysis is fatally biased and must be discarded until the engineering root cause is fixed.
from scipy.stats import chisquare
chi2, p_srm = chisquare(f_obs=[506000, 494000], f_exp=[500000, 500000])
if p_srm < 1e-3:
raise ValueError(f"SRM detected (p={p_srm:.2e}); invalidate experiment readout.")Trying to 're-weight' or down-sample the larger arm in SQL to force a 50/50 count after SRM occurs—this never fixes non-random missingness.
How do SUTVA violations (network interference) break marketplace and social A/B tests, and how do Cluster Randomization and Switchback experiments fix them?
Senior Engineering Answer
Standard A/B tests assume SUTVA (Stable Unit Treatment Value Assumption): one user's outcome depends only on their own assignment. In two-sided marketplaces (rideshare, delivery, auctions) or social networks, treated users cannibalize shared supply or spill over engagement onto control users—causing naive user-level tests to double-count lift or understate true equilibrium effect by 2x+. Fix social spillover via Graph Cluster Randomization (partitioning social graphs via Louvain/balanced min-cut so friends share assignments). Fix spatial/temporal supply cannibalization via Geo-region clustering or Time-Split Switchback experiments (alternating the entire market between A and B over time blocks with washout periods).
# Switchback design: randomize 2-hour market blocks (City x TimeWindow) # Discard first 15-min washout buffer after each switch to prevent carryover bias # Analyze block-level aggregates using randomization inference or cluster-robust SEs
Running user-level randomization on a driver-incentive or surge-pricing test: treated drivers take rides away from control drivers, making the feature look 2x better than when launched to 100% of drivers.
How do you separate Novelty Effect and Primacy Effect from long-term steady-state impact in online product experiments?
Senior Engineering Answer
Novelty effect inflates early metrics because existing users click shiny new UI out of curiosity before reverting; primacy effect temporarily depresses metrics because power users struggle with moved muscle-memory workflows before adapting. Detect them by plotting daily cohort treatment effect stratified by user tenure (brand-new users enrolled on day t vs existing users). New users have no prior habit bias, so comparing new-user lift vs returning-user lift over 2–4 weeks—or running a long-term 5–10% holdout group for 1–3 months on flagship launches—separates transient shock from durable value.
-- Track treatment effect by days-since-first-exposure and new-vs-returning user cohort SELECT is_new_user, DATE_DIFF(event_date, exposure_date, DAY) AS days_exposed, AVG(CASE WHEN variant='trt' THEN metric END) - AVG(CASE WHEN variant='ctrl' THEN metric END) AS lift FROM daily_user_metrics GROUP BY 1, 2;
Declaring victory on a 5-day UI redesign test solely from Day 1–3 click lift without checking returning-user decay curves.
Compare Multi-Armed Bandits (Thompson Sampling / Contextual Bandits) vs Fixed-Horizon A/B Testing, and when bandits are the wrong choice.
Senior Engineering Answer
Fixed A/B tests prioritize statistical inference and unbiased effect estimation across multiple secondary/guardrail metrics, splitting traffic evenly even when one arm underperforms. Multi-Armed Bandits (e.g., Thompson Sampling drawing from Beta/Normal posteriors) minimize cumulative regret by dynamically shifting traffic toward winning arms—ideal for short-lived headlines, ad creatives, or cold-start recommendations where rewards arrive quickly. Bandits are the WRONG choice when rewards are delayed by weeks (retention/LTV), when you have complex multi-metric tradeoffs and guardrail SLAs, or when you need unbiased causal estimates and post-hoc statistical rigor (bandit adaptive sampling creates bias unless analyzed with inverse-propensity estimators).
import numpy as np
def thompson_select(successes, failures):
draws = [np.random.beta(1 + s, 1 + f) for s, f in zip(successes, failures)]
return int(np.argmax(draws))Running naive t-tests on data collected by a Thompson Sampling bandit without propensity reweighting produces invalid confidence intervals.
How would you design an Overall Evaluation Criterion (OEC) and metric governance framework when short-term engagement conflicts with long-term retention?
Senior Engineering Answer
An OEC combines a primary directional North Star proxy (sensitive enough to move in 2 weeks yet validated to correlate causally with long-term LTV/retention) with strict non-negotiable Guardrail Metrics (crash rate, p95 latency, unsubscribe/report rate, margin). For example, optimizing raw clicks rewards clickbait and hurts 90-day retention; instead, weight 'meaningful active sessions' or 'quality-adjusted conversions' validated against historical long-term holdout experiments (surrogate index modeling). Require pre-registered experiment specs naming 1–2 primary OEC metrics, explicit MDEs, and automated guardrail blocks before any test goes live.
# Experiment Pre-Registration Contract: # Primary OEC: 14-day Qualified Retention / LTV Proxy (MDE: +0.5%, alpha=0.05, power=0.8) # Guardrails (non-inferiority): p95 latency < +10ms, spam reports <= +2%, margin >= -0.2% # Decision Rule: Ship only if OEC wins AND zero guardrails regress
Allowing product teams to pick whichever metric moved positively after seeing the dashboard (metric shopping) destroys organizational trust in experimentation.
Data Science Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis Data Science preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to AI & Data Science.
What is the exact definition of a p-value, and what are the three most common misinterpretations in interviews?
Explain Simpson's Paradox with a concrete product analytics example and how stratification resolves it.
Distinguish MCAR, MAR, and MNAR missing data mechanisms, and explain why naive mean imputation distorts variance and correlations.
What are Type I errors, Type II errors, Statistical Power, and Minimum Detectable Effect (MDE) in A/B test sizing?
Why does repeated 'peeking' at A/B test p-values inflate false positives, and how do Sequential Testing (Always-Valid p-values) or Group Sequential designs solve it?
How do you correct for Multiple Hypothesis Testing across 20 metrics or segments, comparing Bonferroni vs Benjamini-Hochberg (FDR)?
Frequently Asked Technical Interview Questions (Data Science)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
What is the Central Limit Theorem (CLT) and when does it break down in practice?
What is the difference between a Confidence Interval and a Bayesian Credible Interval?
How do Survivorship Bias and Selection Bias corrupt product funnels and financial analyses?
When should you use Spearman rank correlation instead of Pearson correlation?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.