Skip to main content
AI & Data Science

Data Science Interview Questions

All Levels (Junior to Staff)16 Questions

Data science interview track: exploratory data analysis, hypothesis testing, p-values, feature engineering, dimensional reduction (PCA), and Pandas/NumPy vectorization.

22 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Data Science Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

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.

Production Code Example
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}")
Common Interview Trap / Anti-Pattern:

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.

Question #2FundamentalJunior

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.

Production Code Example
SELECT
  device_type,
  variant,
  COUNT(*) AS users,
  AVG(converted::float) AS conv_rate
FROM exp_events
GROUP BY 1, 2
ORDER BY 1, 2;
Common Interview Trap / Anti-Pattern:

Do not blindly stratify on variables affected BY the treatment (post-treatment mediators or colliders), as conditioning on a collider induces spurious bias.

Question #3FundamentalJunior

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.

Production Code Example
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)
Common Interview Trap / Anti-Pattern:

Dropping missing rows blindly when data is MAR or MNAR introduces severe selection bias.

Question #4FundamentalJunior

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.

Production Code Example
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))
Common Interview Trap / Anti-Pattern:

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.

Question #5IntermediateMid-Level

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.

Production Code Example
# 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
Common Interview Trap / Anti-Pattern:

Extending an experiment 'just a few more days because p = 0.06 looks promising' invalidates standard p-values just as much as stopping early.

Question #6IntermediateMid-Level

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.

Production Code Example
from statsmodels.stats.multitest import multipletests

reject, p_adj, _, _ = multipletests(raw_p_values, alpha=0.05, method="fdr_bh")
Common Interview Trap / Anti-Pattern:

Running post-hoc subgroup breakdowns across 15 countries and highlighting the one country with p = 0.03 without multiple-testing correction.

Question #7IntermediateMid-Level

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.

Production Code Example
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

pipe = Pipeline([("scaler", StandardScaler()), ("clf", LogisticRegression())])
Common Interview Trap / Anti-Pattern:

Computing global aggregates like 'user_lifetime_orders' across the whole table and using it to predict whether a user converts on their second visit.

Question #8IntermediateMid-Level

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!).

Production Code Example
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)
Common Interview Trap / Anti-Pattern:

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]!

Question #9AdvancedSenior

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.

Production Code Example
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))
Common Interview Trap / Anti-Pattern:

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.

Question #10AdvancedSenior

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.

Production Code Example
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) / n
Common Interview Trap / Anti-Pattern:

Averaging 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.

Question #11AdvancedSenior

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.

Production Code Example
# 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)
Common Interview Trap / Anti-Pattern:

Claiming causal proof from Propensity Score Matching without sensitivity analysis for hidden confounders, or failing to check pre-treatment parallel trends in DiD.

Question #12AdvancedSenior

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.

Production Code Example
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.")
Common Interview Trap / Anti-Pattern:

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.

Question #13StaffPrincipal / Staff

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).

Production Code Example
# 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
Common Interview Trap / Anti-Pattern:

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.

Question #14StaffPrincipal / Staff

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.

Production Code Example
-- 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;
Common Interview Trap / Anti-Pattern:

Declaring victory on a 5-day UI redesign test solely from Day 1–3 click lift without checking returning-user decay curves.

Question #15StaffPrincipal / Staff

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).

Production Code Example
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))
Common Interview Trap / Anti-Pattern:

Running naive t-tests on data collected by a Thompson Sampling bandit without propensity reweighting produces invalid confidence intervals.

Question #16StaffPrincipal / Staff

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.

Production Code Example
# 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
Common Interview Trap / Anti-Pattern:

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 examples

This 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.

JuniorFundamental

What is the exact definition of a p-value, and what are the three most common misinterpretations in interviews?

JuniorFundamental

Explain Simpson's Paradox with a concrete product analytics example and how stratification resolves it.

JuniorFundamental

Distinguish MCAR, MAR, and MNAR missing data mechanisms, and explain why naive mean imputation distorts variance and correlations.

JuniorFundamental

What are Type I errors, Type II errors, Statistical Power, and Minimum Detectable Effect (MDE) in A/B test sizing?

Mid-LevelIntermediate

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?

Mid-LevelIntermediate

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?
CLT states that the sampling distribution of the sample mean approaches normality as sample size grows, regardless of the underlying population distribution—provided observations are independent and the distribution has finite variance. It breaks down at moderate sample sizes for ultra-heavy-tailed power-law data or when observations are clustered/correlated (e.g., repeated events per user).
What is the difference between a Confidence Interval and a Bayesian Credible Interval?
A 95% Frequentist Confidence Interval means that across infinitely repeated experiments, 95% of constructed intervals contain the true fixed parameter—not that the parameter has a 95% probability of lying in this specific interval. A 95% Bayesian Credible Interval directly states that given the prior and observed data, the parameter lies inside the interval with 95% posterior probability.
How do Survivorship Bias and Selection Bias corrupt product funnels and financial analyses?
Survivorship bias evaluates only entities that survived to the end (e.g., analyzing behavior only of retained annual subscribers while ignoring churned users), dramatically overestimating success rates and misattributing winning traits. Selection bias occurs whenever the analyzed cohort is non-randomly filtered (e.g., surveying active users in-app misses frustrated users who already left).
When should you use Spearman rank correlation instead of Pearson correlation?
Pearson measures strictly linear relationships and is heavily distorted by outliers. Spearman computes Pearson correlation on the ranks of two variables, measuring any monotonic relationship (linear or curved) while remaining robust to extreme outliers and monotone transformations.
Complete Learning Ecosystem

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.

Browse All Interview Tracks