Skip to the content.

Data Science Interview Questions: Statistics, SQL, Product Sense and Machine Learning (2027 Prep Guide)

Data science interview questions with answers, grouped the way real interview loops are: probability and statistics, A/B testing and experimentation, SQL, product sense and metrics, machine learning, Python/pandas, case studies, GenAI/LLM questions and behavioral. Every answer is written to be said out loud in an interview, not memorized. The SQL patterns, statistics helpers and ML metrics also live as runnable, tested Python in src/ (standard library only, no installs).

Last reviewed: December 2026. Loop formats change; confirm the rounds for your specific role with the recruiter. Nothing here is an official or leaked company question. Company-specific notes describe patterns frequently reported in public interview experiences.

git clone https://github.com/Ralpberry-Labs/data-science-interview-questions
cd data-science-interview-questions
python3 -m unittest discover -s tests -v   # 20 tests, Python 3.8+, no dependencies
python3 src/sql_exercises.py               # prints every SQL pattern and its result

Table of Contents


What a Data Science Interview Looks Like in 2026

“Data scientist” covers at least three different jobs, and the interview follows the job. Read the job description and figure out which one you are interviewing for before you study anything.

Track Typical titles What the loop leans on Weight of ML
Product / analytics DS Data Scientist (Product Analytics), Product Analyst, DS Analytics SQL, metrics, experiments, product cases, stats Low to medium
ML / modeling DS Data Scientist (ML), Applied Scientist, ML Engineer (some companies) ML theory, coding, modeling cases, ML system design High
Decision science / research Decision Scientist, Economist, Quant UX Researcher Causal inference, experimentation, stats depth Medium

A common loop for a product-facing DS role, as frequently reported in public interview experiences:

  1. Recruiter screen (20-30 min): background, motivation, logistics, compensation expectations.
  2. Technical screen (45-60 min): SQL live, sometimes plus a stats or probability question. Some companies use a timed online assessment instead.
  3. Onsite / virtual loop (3-5 rounds of 45-60 min):
    • SQL or Python/pandas coding
    • Statistics and experimentation
    • Product sense / analytical case (define metrics, diagnose a drop, design a test)
    • ML or modeling (heavier for ML tracks)
    • Behavioral / collaboration
  4. Take-home at some companies, either instead of or before the onsite.

What changed recently:


Study Roadmap: 2, 4 and 8 Week Plans

Assume 1.5-2 hours on weekdays and 3-4 hours on weekend days. Adjust to your gaps: a strong analyst can skip most SQL, a new grad with an ML degree may need product sense most.

8-week plan (coming from scratch or switching careers)

Week Focus Concrete output
1 Probability basics, distributions, Bayes Solve 25 probability problems by hand; finish Seeing Theory chapters 1-3
2 Inference: CIs, hypothesis tests, p-values, power Explain a p-value to a non-technical friend in 60 seconds, out loud
3 SQL fundamentals to window functions SQLBolt, then 20 problems from the LeetCode SQL 50 plan
4 Advanced SQL patterns (retention, streaks, funnels) Rewrite every query in src/sql_exercises.py from memory
5 A/B testing end to end Design 3 experiments in writing: hypothesis, metric, sample size, guardrails, decision rule
6 Product sense and metrics 10 timed product cases (metric definition, root-cause a drop, launch decision)
7 ML concepts and evaluation Explain bias-variance, regularization, trees vs linear models, and every metric in section 7
8 Mock interviews and behavioral 4 full mocks with a friend, 8 STAR stories written down

4-week plan (working analyst or recent grad)

2-week sprint (interview already scheduled)


1. Probability

Interviewers use probability puzzles to see if you can set up a problem cleanly. Say your assumptions first, define events, then compute.

Q1. You roll two fair dice. What is the probability the sum is 7?

There are 36 equally likely ordered outcomes. Sum of 7 comes from (1,6), (2,5), (3,4), (4,3), (5,2), (6,1): 6 outcomes. Answer: 6/36 = 1/6.

Q2. A test for a disease is 99% sensitive and has a 5% false positive rate. 1% of people have the disease. You test positive. What is the chance you have it?

Bayes’ rule: P(D +) = P(+ D)P(D) / P(+).

The point of the question: when the condition is rare, false positives from the large healthy group swamp true positives. Same logic applies to fraud alerts and spam filters. Code: bayes_posterior() in src/stats_tools.py.

Q3. How many people do you need in a room for a better than 50% chance two share a birthday?

Compute the complement: P(all distinct) = 365/365 x 364/365 x … x (365-n+1)/365. It drops below 0.5 at n = 23. The intuition: with 23 people there are 253 pairs, so many chances for a match.

Q4. You flip a fair coin until you get two heads in a row. Expected number of flips?

Let E0 = expected flips from scratch, E1 = expected flips after one head.

Solving: E0 = 2 + E1, E1 = 1 + 0.5 E0, so E0 = 2 + 1 + 0.5 E0, giving E0 = 6. State-based expectation is the trick for every “until X happens” question.

Q5. Expected number of rolls of a die to see all six faces?

Coupon collector: 6/6 + 6/5 + 6/4 + 6/3 + 6/2 + 6/1 = 6 x (1 + 1/2 + … + 1/6) = 14.7. Each new face is a geometric wait whose success probability shrinks.

Q6. Sample k items uniformly from a stream whose length you don’t know.

Reservoir sampling: keep the first k items. For item i (0-indexed, i >= k), draw j uniformly from [0, i]; if j < k replace reservoir[j]. Each item ends up in the sample with probability k/n. Code: reservoir_sample().

Q7. What is the difference between independent and mutually exclusive events?

Mutually exclusive: they can’t both happen, P(A and B) = 0. Independent: knowing one tells you nothing about the other, P(A and B) = P(A)P(B). Two events with non-zero probability that are mutually exclusive are dependent, because if A happens you know B didn’t.

Q8. Which distribution would you use for…?

Situation Distribution Why
Number of signups out of n visitors Binomial Fixed n, independent yes/no trials
Support tickets per hour Poisson Counts of rare events in a fixed window
Time until next ticket Exponential Waiting time between Poisson events
Number of tries until first purchase Geometric Trials until first success
Average order value across many orders Normal (approx.) Central limit theorem
Conversion rate as an unknown parameter (Bayesian) Beta Conjugate prior for a binomial
Revenue per user, income, session length Log-normal or heavy-tailed Skewed, positive, outliers

Q9. Explain the central limit theorem and why it matters at work.

The mean of many independent samples with finite variance is approximately normal, whatever the shape of the underlying data. That is why you can put a confidence interval around average revenue per user even though revenue itself is wildly skewed. Caveat worth mentioning: with very heavy tails (a few whales), “many” can mean a lot more than 30, and your interval will be unstable. Consider winsorizing, a log transform, or a bootstrap.

Q10. A stick is broken at two uniformly random points. Probability the three pieces form a triangle?

A triangle needs every piece shorter than half the stick. Drawing it as a region in the unit square shows the valid area is 1/4. Interviewers mostly want to see you translate the condition into geometry.


2. Statistics and Inference

Q11. What is a p-value, in plain words?

Assuming there is truly no effect, the p-value is the probability of seeing data at least as extreme as what you observed. It is not the probability that the null hypothesis is true, and it is not the probability your result is a fluke. A small p-value says “this data would be surprising if nothing were going on.”

Q12. What is a confidence interval?

A 95% confidence interval comes from a procedure that, if you repeated the study many times, would contain the true value 95% of the time. For a single computed interval, the honest statement is about the method, not “a 95% chance the true value is in this range” (that wording belongs to Bayesian credible intervals). In practice interviewers accept a clear version of either as long as you know the distinction.

Q13. Type I vs Type II error, and power?

Power goes up with sample size, effect size and lower variance, and goes down with a stricter alpha.

Q14. When would you use a t-test, a z-test, a chi-square test or Mann-Whitney?

Test Use when
Two-sample t-test (Welch) Comparing means of a continuous metric between two groups; Welch’s version does not assume equal variances
z-test for proportions Comparing conversion rates with large samples
Chi-square test of independence Two categorical variables, e.g. plan type vs churned
Mann-Whitney U Comparing distributions without assuming normality, e.g. heavily skewed data, ordinal data
Paired t-test Same units measured twice (before/after)

With large A/B test samples, the t-test and z-test give practically the same answer.

Q15. What is the difference between correlation and causation? How do you get at causation without an experiment?

Correlation can come from a confounder, reverse causality or selection. Without randomization you need assumptions: difference-in-differences (parallel trends), regression discontinuity (a sharp cutoff), instrumental variables (something that moves the treatment but not the outcome directly), synthetic control, or matching/weighting on observed confounders. Always say which assumption your method needs and how you would sanity-check it. Free books: Causal Inference: The Mixtape and Causal Inference for the Brave and True.

Q16. Explain Simpson’s paradox with an example.

A trend that appears in every subgroup reverses when the groups are combined, because group sizes differ. Example: a new checkout flow converts better on both mobile and desktop, but overall looks worse because it was shown mostly to mobile users, who convert less in general. The fix is to compare within segments or ensure randomization balances the mix.

Q17. What is regression to the mean?

Extreme measurements tend to be followed by less extreme ones because part of any extreme value is noise. If you target your “worst” stores for a training program, they will likely improve even if the program does nothing. This is why you need a control group.

Q18. How do you handle multiple comparisons?

Testing 20 metrics at alpha = 0.05 gives roughly a 64% chance (1 - 0.95^20) of at least one false positive. Options: pre-register one primary metric, apply Bonferroni (strict, controls family-wise error) or Benjamini-Hochberg (controls false discovery rate, more power), and treat secondary metrics as directional.

Q19. What does a bootstrap do and when would you use it?

Resample your data with replacement many times, recompute the statistic each time, and use the spread of those results as its sampling distribution. Useful for medians, ratios, percentiles and other statistics with no easy formula. Code: bootstrap_ci().

Q20. Explain linear regression assumptions and what happens if they break.

Linearity, independent errors, constant error variance (homoscedasticity), no perfect multicollinearity, and (for small-sample inference) normally distributed errors. Broken homoscedasticity keeps coefficients unbiased but makes standard errors wrong; use robust standard errors. Correlated errors (time series, clustered users) also break standard errors; use clustered errors. Omitted confounders bias the coefficients themselves, which no standard-error fix can solve.

Q21. Frequentist vs Bayesian, in one minute?

Frequentist methods treat parameters as fixed and reason about the long-run behavior of procedures. Bayesian methods treat parameters as uncertain, start with a prior and update to a posterior. Bayesian A/B testing gives statements like “92% probability B is better,” which stakeholders find intuitive, but the result depends on the prior and peeking is not free either. Pick the one your team can explain and use consistently.


3. A/B Testing and Experimentation

This is the most important technical area for product data scientists. Expect at least one full round on it.

Q22. Walk me through designing an A/B test.

  1. Goal and hypothesis. “Showing delivery time on the product page will increase purchase conversion because uncertainty about delivery is a known drop-off reason.”
  2. Unit of randomization. Usually user. Use session only if users won’t notice inconsistency; use cluster (city, team) if there are network effects.
  3. Primary metric that captures the goal and moves within the test window (purchase conversion per user).
  4. Guardrail metrics that must not get worse: page load time, refunds, support contacts, revenue per user.
  5. Sample size from baseline rate, minimum detectable effect (MDE), alpha and power. Translate to duration, and run at least one or two full weekly cycles.
  6. Pre-checks: A/A test or historical variance, logging verified, sample ratio mismatch alarm.
  7. Decision rule written before launch: ship if primary is significant and positive and no guardrail regresses beyond its threshold.
  8. Analysis and readout: effect size with confidence interval, segments as exploration only, recommendation.

Q23. How do you calculate sample size?

For a conversion rate with baseline p and an absolute minimum detectable effect d, per group:

n = (z_(1-alpha/2) + z_(1-beta))^2 x [p1(1-p1) + p2(1-p2)] / d^2

With baseline 10%, MDE of +1 percentage point, alpha 0.05 and power 0.8, that is about 14,750 users per group. Halving the MDE roughly quadruples the sample. Code: sample_size_per_group(); online check: Evan Miller’s calculator.

Q24. What is peeking and why is it a problem?

Checking results repeatedly and stopping as soon as p < 0.05 inflates the false positive rate well beyond 5%, because you are giving noise many chances to cross the line. Fixes: fix the duration up front, or use sequential testing methods (group sequential designs, always-valid p-values) designed for continuous monitoring. Classic read: How Not To Run an A/B Test.

Q25. What is sample ratio mismatch (SRM)?

You planned a 50/50 split but got, say, 50,000 vs 51,200 users. A chi-square test against the planned ratio tells you if that gap is plausible by chance. If it isn’t (p < 0.001 is a common alarm level), something in assignment or logging is broken (bots filtered differently, a redirect that loses users, a crash in one variant), and the results can’t be trusted. Code: srm_chi_square().

Q26. Your test shows a significant lift in the first week that fades by week three. Why?

Check by plotting the treatment effect over time and by looking at new users separately (they have no prior habit to break).

Q27. How do you test a feature with network effects, like a new chat feature or marketplace pricing?

User-level randomization leaks: treated users message control users, or treated buyers take supply from control buyers. Options: cluster randomization (by city, school, social cluster), switchback tests (alternate the whole market between treatment and control over time windows, common in ride-sharing and delivery), or two-sided marketplace designs. Mention the trade-off: fewer independent units means less power.

Q28. What is CUPED?

Controlled-experiment Using Pre-Experiment Data. You adjust each user’s metric using their pre-experiment value of a correlated covariate (often the same metric before the test). This removes variance that has nothing to do with the treatment, so you can detect smaller effects or finish faster. Original paper by Deng, Xu, Kohavi and Walker (2013): PDF.

Q29. The test was significant for the primary metric but revenue dropped. Do you ship?

Not automatically. Quantify both effects with confidence intervals, check if the revenue drop crosses the pre-agreed guardrail, and ask whether the primary metric is a leading indicator of long-term value (retention) that could pay back the short-term revenue loss. A good answer names the trade-off, proposes a follow-up (longer holdout, variant that fixes the revenue issue) and makes a recommendation instead of saying “it depends” and stopping.

Q30. When should you NOT run an A/B test?

Q31. What metrics would you use for a ratio metric like click-through rate per user vs per page view?

If you randomize by user but compute CTR as total clicks / total views, the views are not independent (one heavy user contributes many). Use the delta method or bootstrap by user for the variance, or compute CTR per user and average it. Say which question each version answers: per-view CTR weights heavy users more.

Q32. What is a holdout group?

A small slice of users who are kept away from a set of launched features for weeks or months. It measures the long-term, combined effect of many launches, which short individual tests can’t, and catches effects that decay.

Deep reference (paid book): Trustworthy Online Controlled Experiments by Ron Kohavi, Diane Tang and Ya Xu, companion site experimentguide.com.


4. SQL

SQL is the round most candidates fail by running out of time rather than by not knowing the syntax. Practice until the standard patterns are automatic. All of these run on SQLite in src/sql_exercises.py, with expected outputs asserted in tests/test_all.py.

The 9 patterns that cover most SQL interview questions

Pattern Typical question Tool
Nth highest / distinct Second highest salary DISTINCT ... LIMIT 1 OFFSET n or DENSE_RANK()
Top N per group Top 3 earners per department DENSE_RANK() OVER (PARTITION BY ...)
Retention / cohort Day-1 or week-1 retention by signup date LEFT JOIN on a shifted date, average a 0/1 flag
Gaps and islands Longest login streak date minus ROW_NUMBER() is constant within a streak
Running totals / rolling windows 7-day rolling revenue SUM() OVER (ORDER BY ... ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
Funnel View to cart to checkout rates Conditional aggregation SUM(CASE WHEN ...)
Sequencing Time between first and second order LEAD(), LAG(), ROW_NUMBER()
Median / percentile Median order value ROW_NUMBER() + COUNT() OVER (), or PERCENTILE_CONT where supported
Filtering on aggregates Users with 2+ orders and no order above X GROUP BY ... HAVING

Q33. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after aggregation. You can’t use an aggregate like COUNT(*) in WHERE.

Q34. ROW_NUMBER vs RANK vs DENSE_RANK?

For salaries 100, 90, 90, 80:

salary ROW_NUMBER RANK DENSE_RANK
100 1 1 1
90 2 2 2
90 3 2 2
80 4 4 3

Use DENSE_RANK for “top N distinct values, ties included,” ROW_NUMBER when you need exactly one row per group (latest record per user).

Q35. LEFT JOIN pitfalls?

  1. Putting a filter on the right table in WHERE turns the LEFT JOIN into an INNER JOIN (the NULL rows get filtered out). Put it in the ON clause instead.
  2. Joining to a table with multiple matches per key duplicates rows and inflates sums. Aggregate first, then join.
  3. COUNT(*) counts the NULL-extended rows; COUNT(right_table.id) doesn’t.

Q36. How do NULLs behave?

NULL = NULL is not true (it’s unknown), so use IS NULL. Aggregates like AVG skip NULLs, which silently changes the denominator. NOT IN with a subquery that returns any NULL returns no rows; prefer NOT EXISTS.

Q37. How would you compute day-1 retention?

See day1_retention in the code: join each user to a login exactly one day after signup with a LEFT JOIN, then average a 1/0 flag by cohort. Clarify the definition first: “returned on day 1 exactly” vs “returned within 7 days” give very different numbers.

Q38. Find the longest streak of consecutive login days.

The gaps-and-islands trick: for each user, number their distinct login dates in order. Subtracting the row number from the date gives the same value for every day inside one unbroken streak. Group by that value and count. See longest_streak.

Q39. Explain what a query plan is and how you would speed up a slow query.

The plan shows how the database will execute the query (scans, index lookups, join algorithms). Common fixes: filter early, select only needed columns, add or use an index on join and filter keys, avoid functions on indexed columns in WHERE, pre-aggregate large tables before joining, and in warehouses partition or cluster by date. In analytics interviews, saying “I would check EXPLAIN and avoid joining two un-aggregated event tables” is usually enough.

Practice problems on LeetCode (free problems, verified December 2026)

# Problem Pattern
176 Second Highest Salary Nth highest, NULL handling
178 Rank Scores DENSE_RANK
180 Consecutive Numbers LAG / self-join
185 Department Top Three Salaries Top N per group
262 Trips and Users Joins + conditional rate
550 Game Play Analysis IV Day-1 retention
585 Investments in 2016 Window counts
601 Human Traffic of Stadium Gaps and islands
626 Exchange Seats CASE + ordering
1158 Market Analysis I LEFT JOIN with filter in ON
1174 Immediate Food Delivery II First event per user
1193 Monthly Transactions I Conditional aggregation
1204 Last Person to Fit in the Bus Running total
1321 Restaurant Growth Rolling 7-day window
1934 Confirmation Rate LEFT JOIN + rate

More practice: DataLemur (free and paid tiers), StrataScratch (free and paid tiers), PostgreSQL Exercises (free).


5. Product Sense and Metrics

Product cases test whether you can turn a vague business question into something measurable, and then make a call. There is no single right answer; there are structured and unstructured ones.

A framework for any metrics question

  1. Clarify the product, the user, and the goal. Ask one or two questions, not ten.
  2. Map the user journey (discover, sign up, activate, engage, pay, retain, refer).
  3. Pick a north star metric that reflects value delivered, not just activity.
  4. Add supporting metrics for each step and guardrails for what you must not break.
  5. Define precisely: numerator, denominator, time window, and unit (per user, per session).
  6. Name trade-offs and how you’d detect gaming.

Q40. How would you measure the success of a “Stories” style feature in a messaging app?

Q41. Daily active users dropped 8% yesterday. How do you investigate?

  1. Is it real? Check logging changes, pipeline delays, a tracking deploy, time zone issues, a definition change.
  2. Is it external? Holiday, outage, competitor launch, news event, app store issue, region-wide internet problem.
  3. Segment by platform, app version, country, new vs returning users, acquisition channel. A drop isolated to Android on the newest version points to a release bug.
  4. Check the funnel: fewer opens, or opens with failed loads?
  5. Internal changes: launches, experiments, marketing spend, notification changes.
  6. Summarize with the most likely cause, confidence level and next step.

Interviewers want to see the order: rule out data issues first, then the broad external causes, then segment.

Q42. Should we launch a feature that increases engagement by 2% but decreases revenue by 1%?

Quantify both in money and long-term value if you can. Ask: is engagement a proven leading indicator of retention or revenue for this product? Is the revenue drop concentrated in a segment? Is there a variant that keeps the engagement gain without the loss? Recommend with conditions: for example “launch to 50% while testing a variant, revisit after a 4-week holdout read on retention.”

Q43. How would you pick a north star metric for a food delivery app?

Candidates: orders per week, gross order value, active customers. A strong pick is weekly orders delivered on time to active customers, because it captures value for all three sides (customer gets food, restaurant gets orders, courier gets work) and includes reliability. Pair with guardrails on delivery time, cancellations and courier earnings per hour.

Q44. How do you estimate the number of electric scooters in a city? (estimation)

Structure beats precision. Population, share of people who ride, trips per rider per week, trips per scooter per day, utilization. State every assumption with a round number, compute, then sanity-check against something you know. Say how you would refine it with data.

Q45. Metrics for a B2B SaaS product?

Activation (accounts reaching a defined “aha” action within N days), weekly active teams, seats used / seats paid, net revenue retention, logo churn, time to value, support tickets per account. Mention that B2B decisions involve buyer and user being different people.

Q46. What makes a bad metric?

It is easy to game, lags too much to act on, is a ratio whose denominator can move in the wrong direction, isn’t tied to user value, or can’t be reliably measured. Example: “average session length” rises if your app gets slower.

Practice prompts (do them out loud, 25 minutes each)

  1. A video app’s watch time is up 10% but retention is flat. Explain.
  2. Define success for a new “save for later” button in a shopping app.
  3. Uber Eats-style app: average delivery time rose 3 minutes this week. Diagnose.
  4. How would you measure the health of a two-sided marketplace?
  5. LinkedIn-style “People You May Know”: what metrics, and how would you test a change to it?
  6. Should a streaming service raise prices? What data would you look at?
  7. A ride-share company wants to cut surge pricing. How would you test the impact?
  8. A notification change increased opens but also unsubscribes. What do you do?
  9. Measure the success of an AI writing assistant inside a docs product.
  10. Design a metric dashboard for a new fitness app’s first 90 days.

6. Machine Learning Concepts

Q47. Explain the bias-variance trade-off.

Bias is error from a model that is too simple to capture the pattern (underfitting). Variance is error from a model that is too sensitive to the specific training data (overfitting). More capacity lowers bias and raises variance. You manage it with model choice, regularization, more data, ensembling and cross-validation.

Q48. L1 vs L2 regularization?

Both add a penalty on coefficient size. L2 (ridge) shrinks all coefficients smoothly toward zero and handles correlated features well. L1 (lasso) can set coefficients exactly to zero, so it also does feature selection. Elastic net combines both.

Q49. How does a decision tree split, and why do random forests and gradient boosting beat a single tree?

A tree picks the feature and threshold that most reduce impurity (Gini or entropy for classification, variance for regression). Single trees overfit. Random forests average many deep trees trained on bootstrap samples with random feature subsets, which reduces variance. Gradient boosting adds shallow trees one at a time, each fitting the errors of the current ensemble, which reduces bias; it usually wins on tabular data but needs tuning (learning rate, depth, number of trees) and early stopping.

Q50. Logistic regression: what does it output and how is it trained?

It models log-odds as a linear function of features, so the output passes through the sigmoid to become a probability. It’s trained by maximizing likelihood, equivalently minimizing log loss, typically with gradient-based optimization. Coefficients are interpretable as changes in log-odds per unit of a feature, holding others fixed.

Q51. How do you handle class imbalance (1% fraud)?

Start with the right metric (precision/recall, PR-AUC, cost-weighted), not accuracy. Then: class weights in the loss, resampling (undersample majority, oversample minority, used carefully and only on training folds), threshold tuning based on business costs, and more signal (features). Calibrate probabilities if they will be used as risk scores.

Q52. What is data leakage? Give examples.

Information in training that won’t be available at prediction time. Examples: a “refund issued” flag used to predict refunds; scaling or imputing using statistics from the full dataset before splitting; random splits on time-series data so the model sees the future; duplicate users across train and test. Symptom: suspiciously good offline metrics that collapse in production.

Q53. How do you handle missing data?

First ask why it’s missing (at random, or because of something meaningful like “user never set a birthday”). Options: drop (if rare and random), impute with median/mode or a model, add a “was missing” indicator, or use models that handle missing values natively (many gradient boosting libraries do). Always fit imputation on training data only.

Q54. What is cross-validation and when is plain k-fold wrong?

Split data into k folds, train on k-1, validate on the held-out one, rotate, average. Plain k-fold is wrong for time series (use forward-chaining splits) and for grouped data where the same user appears in many rows (use group k-fold so a user’s rows stay together).

Q55. PCA in one minute?

Finds orthogonal directions of maximum variance and projects data onto the first few. Uses: compress correlated features, visualize, denoise. Caveats: components are linear and hard to interpret, and features must be scaled first.

Q56. K-means: how does it work and what are its weaknesses?

Pick k centers, assign each point to the nearest, move each center to its cluster’s mean, repeat until stable. Weaknesses: you choose k (elbow, silhouette), sensitive to initialization (k-means++ helps) and scale, assumes roughly spherical similar-sized clusters. Code: kmeans_1d() in src/ml_metrics.py.

Q57. How do gradient descent variants differ?

Batch uses all data per step (stable, slow), stochastic uses one example (noisy, fast), mini-batch is the practical middle. Momentum and Adam adapt step sizes and directions to speed up convergence. Learning rate is the most important hyperparameter.

Q58. Explain how a transformer works at a level suitable for a DS interview.

Text is split into tokens, each mapped to a vector. Self-attention lets every token compute a weighted mix of other tokens’ vectors, with weights from query-key similarity, so the model learns which context matters. Stacked attention and feed-forward layers build richer representations. Decoder-only models are trained to predict the next token. Visual explainer: The Illustrated Transformer.


7. Model Evaluation

Metric Formula / idea Use when
Accuracy correct / total Balanced classes and equal error costs only
Precision TP / (TP + FP) False positives are expensive (spam to inbox, wrongly blocking a payment)
Recall TP / (TP + FN) Misses are expensive (fraud, disease screening)
F1 harmonic mean of precision and recall One number when both matter
ROC-AUC P(random positive scores above random negative) Ranking quality, threshold-free
PR-AUC area under precision-recall curve Rare positives; more informative than ROC-AUC there
Log loss penalizes confident wrong probabilities Probabilities themselves matter
RMSE / MAE error size in target units Regression; RMSE punishes big misses more
MAPE average percentage error Forecasts, but breaks near zero actuals
NDCG / MAP ranking with position discount Search and recommendations

Q59. ROC-AUC is 0.95 but the model is useless in production. How?

Leakage, a test set that doesn’t match production, extreme class imbalance where ROC-AUC looks good but precision at the operating threshold is terrible, or the model ranks well but probabilities are badly calibrated for a downstream decision. Check PR-AUC, precision at the chosen threshold, and a time-based holdout.

Q60. How do you choose a classification threshold?

Use business costs: expected value = benefit of true positives minus cost of false positives (and of missed positives). Sweep thresholds on validation data and pick the one that maximizes expected value or meets a constraint (“recall at least 90%,” “review team can handle 500 alerts per day”).

Q61. How would you evaluate a recommender system?

Offline: precision@k, recall@k, NDCG, coverage, diversity, on a time-based split. Online: A/B test on engagement, conversion and long-term retention, plus guardrails on diversity and creator exposure. Offline gains don’t always transfer online, so the online test decides.

Code for precision, recall, F1, ROC-AUC (rank-based) and log loss: src/ml_metrics.py.


8. Python and pandas Coding

Common requests in a Python round for data roles:

Q62. Equivalent of a SQL window function in pandas?

df.groupby("user_id")["amount"].cumsum() for running totals, df.groupby("dept")["salary"].rank(method="dense", ascending=False) for DENSE_RANK, df.groupby("user_id")["date"].shift(-1) for LEAD, df.set_index("date")["revenue"].rolling("7D").mean() for a time-based rolling window.

Q63. apply is slow on 10 million rows. What do you do?

Vectorize with column operations or np.where, use built-in groupby aggregations, convert repeated strings to category dtype, filter before joining, and process in chunks or move the work to SQL/a warehouse if it’s really big. Profile before optimizing.

Q64. What does merge do with duplicate keys?

It produces every combination of matching rows (a many-to-many join explodes). Use validate="one_to_one" or "many_to_one" in pd.merge to catch it early.

Free reference: Python for Data Analysis, 3rd edition by pandas creator Wes McKinney (free to read online) and the Python Data Science Handbook by Jake VanderPlas (free online).


9. ML Case Studies and System Design

A case round asks you to design a modeling solution to a business problem. A structure that works:

  1. Business goal and success metric (what decision does the model drive?).
  2. Framing: classification, regression, ranking, forecasting? What is the label and how is it collected?
  3. Data and features, including what’s available at prediction time.
  4. Baseline (a rule or simple model) before anything fancy.
  5. Model choice with reasons.
  6. Offline evaluation with a split that mimics production.
  7. Online evaluation (A/B test) and monitoring (drift, latency, feedback loops).
  8. Risks: fairness, privacy, abuse, cold start.

Q65. Design a churn prediction model for a subscription app.

Q66. Design a fraud detection system for card payments.

Real-time scoring with tight latency, extreme imbalance, adversaries who adapt, and delayed labels (chargebacks arrive weeks later). Features: velocity (transactions per card in last hour), device and location mismatches, merchant risk, amount relative to history. Layer rules for known patterns with a model for the rest, route mid-score cases to manual review, and monitor drift continuously.

Q67. Build a model to estimate delivery time.

Regression with features for distance, restaurant prep-time history, time of day, weather, courier supply. Evaluate MAE plus the share of orders that arrive later than promised, since lateness hurts more than earliness. Consider predicting a distribution or quantiles and quoting a conservative percentile.

Good free reading: Chip Huyen’s ML Interviews Book. Paid: Designing Machine Learning Systems by Chip Huyen (O’Reilly).


10. GenAI and LLM Questions

These now appear in data science loops, especially at companies shipping AI features.

Q68. How would you evaluate an LLM-powered support chatbot?

Combine three layers:

Then A/B test model or prompt changes like any other feature.

Q69. What is retrieval-augmented generation (RAG) and how would you measure whether retrieval is working?

The system fetches relevant documents and puts them into the prompt so the model answers from them. Measure retrieval separately from generation: recall@k of the passages that contain the answer, and answer faithfulness to the retrieved text. A wrong answer with the right passage retrieved is a generation problem; a wrong answer without it is a retrieval problem.

Q70. How do you A/B test a feature whose output is non-deterministic?

Randomize users as usual; the non-determinism is part of the treatment. Make sure model version, prompt and temperature are logged per request, keep them fixed during the test, and watch cost and latency as guardrails. Larger variance can mean you need more samples.

Q71. What can go wrong when you use an LLM to label training data?

Systematic bias (it agrees with itself, prefers certain styles), label leakage if the same model later is evaluated on that data, drift when the model version changes, and confident wrong labels on edge cases. Mitigate with a human-labeled gold set, agreement checks and periodic audits.

Q72. You used an AI assistant to write a SQL query in the interview. How do you check it?

Read the joins for fan-out, check filters in WHERE vs ON, check date boundaries and time zones, run it on a small known case where you can compute the answer by hand, and compare row counts before and after each join. Say these checks out loud; that is often exactly what is being evaluated.


11. Behavioral Questions for Data Scientists

Use STAR (Situation, Task, Action, Result) and keep the “Action” part about what you did. Quantify results.

Question What they’re probing
Tell me about an analysis that changed a decision. Impact, communication
Tell me about a time your analysis was wrong. Ownership, rigor
Describe a time you disagreed with a PM about a launch. Influence without authority
How did you explain a complex result to a non-technical audience? Communication
Tell me about a project with messy or missing data. Pragmatism
A stakeholder wanted a specific answer from the data. What did you do? Integrity
When did you choose a simpler method over a sophisticated one? Judgment
Tell me about an AI-generated output you didn’t trust. Verification habits (newer question)

Prepare 6-8 stories that can each answer several questions. For a full method, see the Behavioral Interview Handbook.


Take-Home Assignments

Typical prompt: a CSV or small database, a vague question (“what drives retention?”), 3-8 hours suggested.

How to do well:

  1. Lead with the answer. First page: question, recommendation, 3 key findings, caveats.
  2. Show data checks: row counts, duplicates, missing values, date ranges, anything odd.
  3. One or two clear charts per finding, labeled, with the takeaway in the title.
  4. Simple methods done well beat a complex model you can’t explain.
  5. Limitations and next steps: what data or experiment would make you more confident.
  6. Reproducible: a notebook or script that runs top to bottom, with a short README.
  7. Respect the time box. Saying “with more time I would…” is fine and expected.

Best Resources (Free and Paid)

Statistics and probability

Resource Type Cost Best for
Seeing Theory (Brown University) Interactive visual Free Intuition for distributions and inference
OpenIntro Statistics Textbook Free PDF Solid intro stats with exercises
Think Stats, 3rd edition by Allen Downey Book, Python Free online Programmers learning stats
Think Bayes 2 by Allen Downey Book, Python Free online Bayesian thinking
MIT 18.05 Introduction to Probability and Statistics Course Free Structured probability + stats
StatQuest with Josh Starmer YouTube Free Short, clear explanations of stats and ML

Experimentation and causal inference

Resource Cost Notes
Trustworthy Online Controlled Experiments (Kohavi, Tang, Xu), site Paid book The standard reference for A/B testing at scale
Evan Miller’s A/B testing articles and tools Free Peeking, sample size
CUPED paper Free Variance reduction
Microsoft Experimentation Platform research Free Articles on real experimentation pitfalls
Causal Inference: The Mixtape by Scott Cunningham Free online DiD, RDD, IV, synthetic control
Causal Inference for the Brave and True by Matheus Facure Free online Same ideas in Python

SQL

Resource Cost Notes
SQLBolt Free Fastest interactive intro
LeetCode SQL 50 Free Curated interview-style set
DataLemur Free tier + paid Company-tagged SQL questions
StrataScratch Free tier + paid SQL and pandas questions
PostgreSQL Exercises Free Deliberate practice on joins and aggregates
SQLite window functions docs / PostgreSQL window tutorial Free The official references

Machine learning

Resource Cost Notes
An Introduction to Statistical Learning (ISLR / ISLP) Free PDF Best single ML book for DS interviews; R and Python editions
The Elements of Statistical Learning Free PDF Deeper, more mathematical
Mathematics for Machine Learning Free PDF Linear algebra, calculus, probability for ML
Google Machine Learning Crash Course Free Practical ML basics
scikit-learn User Guide Free Clear explanations of most classical models
Stanford CS229 Free materials ML theory
Dive into Deep Learning Free Deep learning with code
Neural Networks: Zero to Hero by Andrej Karpathy Free Build neural nets and a GPT from scratch
Forecasting: Principles and Practice (3rd ed.) Free online Time series

Interview-specific

Resource Cost Notes
Ace the Data Science Interview by Nick Singh and Kevin Huo, site Paid book Broad question bank across all areas
ML Interviews Book by Chip Huyen Free ML roles, process and questions
alexeygrigorev/data-science-interviews Free Community Q&A on theory
Interview Query Free tier + paid Company-tagged questions, guides
Kaggle Learn Free Short hands-on courses for pandas, SQL, ML

Best pick if you only have time for three: ISLR/ISLP for ML, the LeetCode SQL 50 for SQL, and Kohavi’s book (or, if you can’t buy it, Evan Miller’s articles plus section 3 here) for experimentation. Product sense comes from practice, not reading: do the 10 prompts above out loud.


FAQ

What questions are asked in a data science interview? Usually a mix of SQL, probability and statistics, A/B testing, product or business cases, machine learning concepts, Python coding and behavioral questions. The balance depends on whether the role is analytics-focused or ML-focused.

How do I prepare for a data science interview in 4 weeks? Week 1 stats and SQL, week 2 experimentation and product cases, week 3 ML and evaluation, week 4 mocks and behavioral stories. See the roadmap.

Is SQL or Python more important for data science interviews? For product and analytics roles, SQL is tested more often and more strictly. For ML roles, Python and ML theory matter more, but most loops still include some SQL.

How much math do I need? Comfort with probability, basic statistics, linear algebra intuition (vectors, matrices, dot products) and derivatives at the level of gradient descent. Deep proofs are rare outside research roles.

Do data science interviews include LeetCode-style algorithms? Sometimes, usually easy to medium for DS roles. ML engineer roles often have standard software engineering coding rounds.

What is a product sense interview for data scientists? An open-ended case where you define metrics, investigate a metric change or decide on a launch using data. Structure and judgment matter more than any specific answer.

Can I use ChatGPT or other AI tools in a data science interview? Only if the company says so. Some rounds now explicitly allow AI tools and evaluate how you verify the output; others ban them. Ask the recruiter.

What’s a good answer to “what is a p-value”? “If there were truly no effect, it’s the probability of seeing a result at least this extreme. A small p-value means the data would be surprising under no effect.” Then mention what it’s not.

How do data analyst interviews differ from data scientist interviews? Analyst loops focus on SQL, dashboards, business cases and stakeholder communication, with lighter statistics and rarely ML. Data scientist loops add experimentation depth and often modeling.

How should I answer salary questions? Avoid naming a number early when you can, and research ranges first. See the Salary Negotiation Guide.


Where to Go Next


Contributing

Corrections and new questions are welcome.

License

Content and code are released under the MIT License. Copyright (c) 2026 Ralpberry Labs.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.