New batches starting this week ยท Limited seats

Data Science Interview Questions and Answers 2026 (60 Questions)

60 data science interview questions with clear, correct answers covering statistics, SQL, pandas, EDA, A/B testing, ML basics, GenAI-assisted analysis, product cases and real-world scenarios.

Data science interview questions 2026: 60 questions on statistics, SQL, pandas, A/B testing, case studies and communicating insights
Last updated ยท 44 min read ยท 9,672 words

Data science interview questions in 2026 test far more than whether you can name an algorithm. Interviewers want to see that you can reason correctly about uncertainty, pull the right numbers with SQL and pandas, design an experiment that will not fool you, and turn a result into a decision a business owner can act on. This guide collects 60 high-value data science interview questions with answers written the way an experienced data scientist explains them in a real interview loop, from statistics and SQL to A/B testing, GenAI-assisted analysis and product case questions.

How to use this guide

  • Freshers and analysts moving into data science are usually tested on statistics fundamentals, SQL joins and aggregation, pandas basics and clean EDA. Sections one to four matter most.
  • Mid-level data scientists get window functions, experiment design, metric choice, model evaluation and "walk me through how you would answer this" questions with follow-ups.
  • Senior candidates are judged on experimentation pitfalls, causal reasoning without an experiment, metric definitions across teams, and how they communicate uncertainty to leadership. The case and scenario sections are where these interviews are decided.
  • Write the SQL and pandas snippets yourself on a small sample dataset. Saying an answer out loud with an example from your own work beats a memorised paragraph every time.

Contents

Statistics and probability

1. What is data science, and how does a data scientist's work differ from a data analyst's or an ML engineer's?

Answer: Data science is the practice of using statistics, programming and domain knowledge to extract reliable insight from data and to build models that support decisions. The roles overlap but have different centres of gravity. A data analyst mostly answers "what happened and why" with SQL, dashboards and descriptive statistics. A data scientist adds inference, experimentation and predictive modelling: "will this change work, and how sure are we?" An ML engineer focuses on getting models into production reliably: pipelines, serving, monitoring and scale. A data engineer builds the pipelines and warehouses all three depend on.

Interview tip: Do not define data science as "algorithms that find hidden patterns". Describe the decision it supports. "I help the business decide X using evidence Y" is a stronger answer than a list of tools.

2. Walk me through the steps of a data science project.

Answer: A project that ends in a decision usually follows these steps:

  1. Frame the business problem and the decision it feeds, with a success metric agreed up front.
  2. Find and understand the data: sources, grain, definitions, known quality issues, access and privacy constraints.
  3. Clean and prepare: missing values, duplicates, joins, time zones, feature construction.
  4. Explore distributions and relationships; form and narrow hypotheses.
  5. Analyse or model: a test, an experiment, a forecast or a predictive model, starting from a simple baseline.
  6. Validate on held-out or new data and sanity-check against domain knowledge.
  7. Communicate and deploy: a recommendation, a dashboard or a model in production.
  8. Monitor and iterate: track whether the result holds and whether the model drifts.

Interview tip: Interviewers listen for step one. Candidates who jump straight to "I trained XGBoost" without saying what decision the model serves lose points.

3. Explain the common probability distributions and when each one shows up in real data.

Answer:

DistributionWhat it modelsTypical example
Bernoulli / binomialSuccess or failure; number of successes in n independent trialsConversions out of visitors in an experiment arm
PoissonCount of events in a fixed interval, mean equal to varianceSupport tickets per hour, claims per day
Negative binomialCounts with variance larger than the mean (overdispersion)Orders per customer, where a few customers order a lot
ExponentialWaiting time between Poisson events; memorylessTime until the next call arrives at a contact centre
NormalSymmetric, thin-tailed values; sampling distributions of meansMeasurement error, averages over large samples
Log-normal / heavy-tailedPositive, right-skewed valuesRevenue per user, transaction amounts, session length

The practical skill is recognising when an assumption breaks. Revenue per user is almost never normal, and count data with a variance far above its mean is not Poisson.

4. What does the Central Limit Theorem say, and what does it not say?

Answer: For independent, identically distributed observations with finite variance, the sampling distribution of the sample mean approaches a normal distribution as the sample size grows, with standard error equal to the standard deviation divided by the square root of n. That is why t-tests and z-tests on averages work even when the raw data is skewed.

It does not say that the data itself becomes normal, and it says nothing about how large n must be. Heavily skewed metrics such as revenue per user need far larger samples before the approximation is good, and a few extreme values can dominate the mean. It also assumes independence: if users appear many times or sessions are clustered within users, the effective sample size is smaller than the row count.

5. What is the difference between expected value and mean?

Answer: The expected value is a property of a random variable or probability distribution: the probability-weighted average of all possible outcomes, a theoretical quantity. The sample mean is a statistic computed from observed data, and it is an estimate of the expected value. By the law of large numbers, the sample mean converges to the expected value as the sample grows. In conversation the words are often used interchangeably, but in an interview the distinction between a population parameter and its estimate is exactly what is being tested.

6. Explain hypothesis testing, Type I and Type II errors, and statistical power.

Answer: You state a null hypothesis (usually "no effect" or "no difference") and an alternative. You pick a significance level alpha before looking at the data, compute a test statistic, and reject the null if the result would be sufficiently unlikely under it.

  • Type I error (false positive): rejecting a true null. Its probability is alpha.
  • Type II error (false negative): failing to reject a false null. Its probability is beta.
  • Power is one minus beta: the probability of detecting an effect of a given size if it really exists. Power rises with sample size, effect size and alpha, and falls with variance.

Real-world example: A fraud model that blocks legitimate payments is making Type I errors from the customer's point of view; one that lets fraud through is making Type II errors. The business cost of each decides where you set the threshold, not a textbook default.

7. What is a p-value, and what are the common ways people misread it?

Answer: A p-value is the probability, assuming the null hypothesis and the test's assumptions are true, of observing a result at least as extreme as the one you got. A small p-value means the data would be surprising if there were no effect.

What it is not:

  • It is not the probability that the null hypothesis is true.
  • It is not the probability that the result happened "by chance".
  • It is not a measure of effect size or business importance: a tiny, useless effect can have a very small p-value with enough data.
  • A p-value above alpha does not prove there is no effect; the test may simply be underpowered.

Interview tip: Always pair a p-value with an effect size and a confidence interval. "The lift is small but precisely estimated" and "the lift could be large or zero" are very different messages with similar p-values.

8. How do you correctly interpret a 95 percent confidence interval?

Answer: A 95 percent confidence interval comes from a procedure that, if you repeated the sampling many times, would produce intervals containing the true parameter in 95 percent of those repetitions. For any single computed interval, the frequentist framework does not say there is a 95 percent probability the true value lies inside it; the parameter is fixed and the interval either contains it or not. If you want a direct probability statement about the parameter, that is a Bayesian credible interval, which requires a prior.

Practically, the width matters as much as the location. An interval for a conversion lift that spans from slightly negative to strongly positive says "we do not know yet", which is a useful and honest answer.

9. Explain Bayes' theorem with a worked example. What are the prior and the likelihood?

Answer: Bayes' theorem updates a belief with evidence: P(A given B) = P(B given A) ร— P(A) / P(B). The prior P(A) is what you believed before the evidence. The likelihood P(B given A) is how probable the evidence is if A is true. The posterior P(A given B) is the updated belief.

Real-world example (hypothetical numbers): Consider a bank where 1 in 1,000 transactions is fraudulent. A rule flags 99 of every 100 fraudulent transactions and also flags 5 of every 100 legitimate ones. If a transaction is flagged, the probability it is fraud is 0.99 ร— 0.001 / (0.99 ร— 0.001 + 0.05 ร— 0.999), roughly 0.019, or about 2 in 100. Most alerts are false alarms because the base rate is so low. That is base-rate neglect, and it is why fraud and medical screening teams care about precision, not just detection rate.

10. What types of sampling bias can occur, and how do you guard against them?

Answer: The common ones are:

  • Selection bias: the sample is chosen in a way related to the outcome, for example analysing only customers who opened the app.
  • Undercoverage: part of the population cannot be sampled, such as an online survey that misses customers who only visit branches.
  • Survivorship bias: looking only at units that survived a process, such as studying retained customers to explain retention.
  • Non-response and voluntary-response bias: people who answer surveys or leave reviews differ from those who do not.

Guards include random sampling where possible, comparing the sample's profile with the known population, weighting, and being explicit in the write-up about who the result applies to.

11. Correlation versus causation: how do confounders and Simpson's paradox mislead analyses?

Answer: Correlation measures association; causation means changing X changes Y. A confounder is a variable that affects both, creating an association without a causal link. Customers who use a premium feature may churn less simply because they are more engaged in the first place.

Simpson's paradox is when a trend that appears in every subgroup reverses when the groups are combined, because group sizes differ. A hospital can have higher survival rates than another in both mild and severe cases yet lower overall, if it treats far more severe cases. The fix is to identify the variable that drives group composition and analyse within it, or better, use an experiment.

12. Why do we use resampling methods such as the bootstrap and permutation tests?

Answer: Resampling estimates uncertainty or tests hypotheses when formulas are awkward or assumptions are doubtful.

  • Bootstrap: sample with replacement from your data many times, compute the statistic each time, and use the spread as a standard error or confidence interval. Useful for medians, ratios and percentiles.
  • Permutation test: shuffle group labels many times to build the distribution of the statistic under the null, then see where the observed value falls.
  • Cross-validation: repeatedly split data into train and validation folds to estimate how a model generalises.

The catch: resample at the right unit. If you have many sessions per user, bootstrap users, not sessions, or the interval will be too narrow.

13. What is power analysis, and how do you estimate sample size for a test?

Answer: Power analysis determines the sample size needed to detect a minimum effect you care about with chosen alpha and power, before the experiment starts. Inputs are the baseline metric and its variance, the minimum detectable effect, alpha and power. A rough rule for comparing two means at alpha 0.05 two-sided with power 0.8 is about 16 ร— variance / (effect size squared) per group. Smaller effects need quadratically more data: halving the effect you want to detect roughly quadruples the sample.

Interview tip: Say where the minimum detectable effect comes from: the smallest change that would justify the cost of shipping. Picking it after seeing the data defeats the purpose.

SQL for data science

14. Explain the SQL join types, and what is the most common join mistake in analysis?

Answer: INNER JOIN keeps matching rows only. LEFT JOIN keeps every row from the left table and fills unmatched right-side columns with NULL. FULL OUTER JOIN keeps unmatched rows from both. CROSS JOIN produces every combination. An anti-join finds rows with no match:

-- customers who never placed an order
SELECT c.customer_id
FROM customers c
LEFT JOIN orders o
  ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;

The most common mistake is fan-out: joining on a key that is not unique on one side, which silently duplicates rows and inflates sums. Before joining, check the grain of each table (one row per what?) and compare row counts before and after.

15. What is the difference between WHERE and HAVING, and between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

Answer: WHERE filters rows before grouping; HAVING filters groups after aggregation. COUNT(*) counts rows, COUNT(column) counts non-NULL values, and COUNT(DISTINCT column) counts unique non-NULL values.

SELECT city,
       COUNT(*) AS orders,
       COUNT(DISTINCT customer_id) AS buyers,
       AVG(CASE WHEN status = 'returned'
                THEN 1.0 ELSE 0 END) AS return_rate
FROM orders
WHERE order_date >= DATE '2026-01-01'
GROUP BY city
HAVING COUNT(*) >= 100;

The CASE inside AVG is conditional aggregation, a pattern interviewers love. Using 1.0 avoids integer division in databases that truncate integer averages or ratios.

16. How do ROW_NUMBER, RANK and DENSE_RANK differ? Write a top-N-per-group query.

Answer: All three number rows within a window. ROW_NUMBER gives unique sequential numbers, breaking ties arbitrarily unless the ORDER BY is fully deterministic. RANK gives ties the same rank and leaves gaps (1, 1, 3). DENSE_RANK gives ties the same rank without gaps (1, 1, 2).

-- top 3 orders by amount for each customer
SELECT *
FROM (
  SELECT o.*,
         ROW_NUMBER() OVER (
           PARTITION BY customer_id
           ORDER BY amount DESC, order_id
         ) AS rn
  FROM orders o
) t
WHERE rn <= 3;

Interview tip: Say which function matches the business rule. "Top three products, ties included" needs RANK or DENSE_RANK, not ROW_NUMBER.

17. How do you compute day-over-day change, running totals and moving averages in SQL?

Answer: With window functions over an ordered set:

SELECT order_date,
       revenue,
       revenue - LAG(revenue) OVER (
         ORDER BY order_date) AS change_vs_prev,
       SUM(revenue) OVER (
         ORDER BY order_date) AS running_total,
       AVG(revenue) OVER (
         ORDER BY order_date
         ROWS BETWEEN 6 PRECEDING
              AND CURRENT ROW) AS avg_7_rows
FROM daily_revenue;

Two traps: a ROWS frame counts rows, not days, so missing dates make "seven rows" span more than a week (fill the calendar first with a date spine); and the default frame for SUM with ORDER BY is RANGE, which treats rows with equal dates as peers and includes them together.

18. How do you find and remove duplicate records?

Answer: First define what "duplicate" means in business terms, then find them:

SELECT LOWER(TRIM(email)) AS email_key,
       COUNT(*) AS n
FROM users
GROUP BY LOWER(TRIM(email))
HAVING COUNT(*) > 1;

To keep only the latest record per key in analysis, rank and filter rather than deleting:

SELECT *
FROM (
  SELECT u.*,
         ROW_NUMBER() OVER (
           PARTITION BY LOWER(TRIM(email))
           ORDER BY updated_at DESC
         ) AS rn
  FROM users u
) t
WHERE rn = 1;

Normalising the key (case, whitespace, formatting of phone numbers) usually finds more duplicates than exact matching. Deleting from a production table is a data engineering change with a review, not an analysis step.

19. What NULL-handling pitfalls catch people out in SQL?

Answer:

  • NOT IN with NULLs: if the subquery returns any NULL, WHERE id NOT IN (subquery) returns no rows, because the comparison becomes unknown. Use NOT EXISTS instead.
  • Filtering the right table in WHERE after a LEFT JOIN discards the NULL rows and quietly turns it into an inner join. Put that condition in the ON clause.
  • NULL = NULL is not true; use IS NULL, or IS NOT DISTINCT FROM where supported.
  • Aggregates ignore NULLs: AVG(score) averages only non-NULL scores, which may or may not be what the metric definition intends. Decide whether missing means zero and use COALESCE explicitly.

20. Your query on a large warehouse table is slow. How do you approach it?

Answer: Read the query plan first (EXPLAIN, or the warehouse's query profile) rather than guessing. Then check the usual causes: scanning a full table when the data is partitioned or clustered by date and you did not filter on it; selecting every column in a columnar warehouse; a fan-out join producing huge intermediate results; functions on the filter column that prevent index or partition pruning; and repeated subqueries that could be one CTE or a pre-aggregated table. In row-store databases such as PostgreSQL, an index on join and filter columns often matters most. Finally, ask whether the question needs raw events at all; a daily aggregate table may answer it in a fraction of the cost.

pandas and data wrangling

21. Which Python libraries do you use for data analysis, and what is each one for?

Answer: NumPy for arrays and vectorised numerics; pandas for tabular wrangling; Matplotlib and Seaborn (or Plotly) for charts; SciPy and statsmodels for statistical tests and regression with proper inference output; scikit-learn for classical machine learning, preprocessing and evaluation. For larger-than-comfortable data, Polars and DuckDB are increasingly common for fast single-machine work, and PySpark for distributed processing. Jupyter notebooks for exploration, but production logic belongs in tested modules.

Interview tip: Mention why you would pick statsmodels over scikit-learn for a regression: you want coefficients, standard errors and confidence intervals for inference, not just predictions. If your Python foundations are shaky, fix that first; the Python training course covers the core language these libraries depend on.

22. How do you handle missing data? Explain MCAR, MAR and MNAR.

Answer: Start by asking why the data is missing, because the right treatment depends on the mechanism:

  • MCAR (missing completely at random): missingness is unrelated to anything. Dropping rows loses power but does not bias results.
  • MAR (missing at random): missingness depends on other observed variables, for example income missing more often for younger customers. Imputation conditioned on those variables is reasonable.
  • MNAR (missing not at random): missingness depends on the missing value itself, such as high earners declining to state income. No simple imputation fixes this; you need domain assumptions or sensitivity analysis.

In practice: measure missingness by column and segment, add a "was missing" indicator when it carries signal, impute inside the cross-validation pipeline (not before splitting), and say clearly in the write-up what you assumed.

23. Explain groupby with agg and transform, and how you avoid merge mistakes in pandas.

Answer: groupby().agg() reduces each group to one row; groupby().transform() returns a result aligned to the original rows, which is ideal for "share of group total" or "group mean" features.

df = orders.merge(customers, on="customer_id",
                  how="left",
                  validate="many_to_one")

df["share_of_spend"] = (
    df["amount"]
    / df.groupby("customer_id")["amount"]
        .transform("sum")
)

summary = df.groupby("city").agg(
    orders=("order_id", "count"),
    revenue=("amount", "sum"),
)

The validate argument makes pandas raise an error if the join keys are not unique where you expect them to be, catching fan-out before it corrupts totals. Also use indicator=True to see how many rows matched, and avoid row-wise apply when a vectorised operation exists.

24. How do you detect and deal with outliers?

Answer: Detect with plots (box plots, histograms on a log scale), the IQR rule, z-scores on roughly symmetric data, or robust methods such as median absolute deviation. Then decide what the outlier is before touching it:

  • Data error (a test transaction, a unit mix-up, a duplicate): fix or remove it, and log the rule.
  • Genuine but extreme (a large corporate order): keep it, but consider robust statistics such as the median, winsorising or capping for a specific test, or analysing that segment separately.

Never delete outliers just because they make a result less significant. In an experiment, any capping rule must be decided before looking at results and applied to both arms equally.

25. Your dataset does not fit in memory. What do you do?

Answer: In rough order: load only the columns and rows you need; downcast dtypes (category for low-cardinality strings, smaller integer and float types); read in chunks and aggregate incrementally; store data as Parquet rather than CSV so reads are columnar and compressed; push the work to where the data lives with SQL in the warehouse; use DuckDB or Polars, which handle larger-than-memory or out-of-core workloads on one machine efficiently; and move to Spark only when the data or the compute genuinely needs a cluster. Often the right answer is that you do not need the raw events at all, only a well-designed aggregate.

26. How do you encode categorical variables, and how can preprocessing leak information?

Answer: One-hot encoding works for low-cardinality nominal variables. Ordinal encoding suits genuinely ordered categories. For high-cardinality variables such as pincode or merchant ID, use target encoding (with out-of-fold computation and smoothing), frequency encoding, hashing or a model that handles categories natively.

Leakage happens when preprocessing uses information the model would not have at prediction time: computing target encodings, scaling parameters or imputation values on the full dataset before the train/test split; or using features recorded after the outcome. Fit every transformer inside a scikit-learn Pipeline so it is learned only on training folds.

EDA and visualisation

27. How do you approach exploratory data analysis on a dataset you have never seen?

Answer: I start with structure and trust before patterns:

  1. Grain and keys: what is one row? Is the key unique? How many rows per day?
  2. Quality: missingness, duplicates, impossible values, sudden jumps in volume that signal a pipeline change.
  3. Univariate distributions: shape, skew, outliers. For skewed metrics I report the median and percentiles alongside the mean.
  4. Relationships: the target against key features, and segments (city, channel, device, cohort).
  5. Time: trends, seasonality, festive-season effects and definition changes over time.
  6. Write down hypotheses and what would confirm or reject them, so EDA feeds the next step instead of becoming endless chart-making.

28. How do you choose the right chart for a question?

Answer: Choose by the question, not the data type:

QuestionChart
How does a metric change over time?Line chart
How do categories compare?Sorted horizontal bar chart
What does the distribution look like?Histogram, box plot or ECDF
How do two numeric variables relate?Scatter plot, with transparency or binning for many points
How do parts make up a whole?Stacked bar; a pie only for two or three parts
Where is a funnel losing users?Funnel or step bar chart with conversion between steps

Then strip everything that does not help answer the question, and put the conclusion in the chart title.

29. What makes a visualisation misleading?

Answer: Truncated y-axes on bar charts that exaggerate small differences; dual y-axes that imply a relationship by choosing scales; cumulative charts that always go up and hide a slowing trend; averages that hide very different segments; inconsistent time windows across panels; 3D effects and area encodings people cannot judge accurately; and missing uncertainty, showing a point estimate with no interval. Showing a metric without its denominator is another classic: "complaints doubled" means little if orders tripled.

Experimentation and A/B testing

30. What is the aim of A/B testing, and how do you design one properly?

Answer: An A/B test randomly assigns units to a control and one or more variants so that the only systematic difference is the change itself. That lets you estimate the causal effect of the change on chosen metrics, rather than an association. A sound design specifies, before launch:

  • The hypothesis and the decision each outcome would trigger.
  • The randomisation unit (user, account, store, session) and the analysis unit, which should match.
  • One primary metric, guardrail metrics and the minimum detectable effect.
  • Sample size and duration from a power analysis, covering full weekly cycles.
  • The analysis method and any outlier rules.

31. How do you choose metrics for an experiment?

Answer: A primary metric should be sensitive to the change, aligned with long-term value and hard to game. Guardrail metrics protect against harm: latency, error rate, unsubscribes, refunds, support contacts. Diagnostic metrics explain the mechanism (clicks on the new button). Beware metrics that move easily but do not matter, such as click-through rate on a redesigned banner that cannibalises other clicks. For ratio metrics like revenue per session where the randomisation unit is the user, use the delta method or bootstrap at the user level, because sessions from the same user are not independent.

32. What is the peeking problem, and how does testing many metrics or variants inflate false positives?

Answer: Peeking means checking a fixed-horizon test repeatedly and stopping as soon as p falls below alpha. Each look is another chance for noise to cross the threshold, so the real false-positive rate is much higher than the nominal alpha. Fixes: commit to a sample size and analyse once, or use a method built for continuous monitoring such as sequential testing or always-valid inference.

The same inflation happens with many metrics, many variants or many segments. If you test twenty independent metrics at alpha 0.05, you should expect about one false "win" by chance. Pre-register the primary metric, treat everything else as exploratory, and apply corrections such as Bonferroni or Benjamini-Hochberg (false discovery rate) when making multiple confirmatory claims.

33. What is a sample ratio mismatch, and why does it invalidate a test?

Answer: A sample ratio mismatch (SRM) occurs when the observed split between arms differs from the designed split by more than chance allows, for example a planned even split that comes out noticeably uneven over a large sample. A chi-square test on the counts detects it. SRM means something in assignment or logging is broken: a redirect that drops some users, a bot filter applied unevenly, a crash in one variant that stops events being recorded. Because the arms are no longer comparable, the effect estimate cannot be trusted, however significant it looks. Investigate and fix the cause rather than reweighting.

34. What are novelty effects, primacy effects and interference between units?

Answer: A novelty effect is a temporary lift because a change is new; a primacy effect is a temporary dip while users adjust to it. Both are detected by plotting the treatment effect over time and by looking at new versus returning users separately. Interference breaks the assumption that one unit's treatment does not affect another's outcome. In marketplaces, ride-hailing and food delivery, giving riders in the treatment group a discount uses up drivers that control riders also need; in social products, users influence each other. Mitigations include cluster randomisation (by city or region), switchback designs that alternate treatment over time windows, and measuring effects at the market level.

35. What can you do when an A/B test is not possible or is underpowered?

Answer: For underpowered tests, reduce variance: CUPED uses each unit's pre-experiment metric as a covariate and can shrink confidence intervals substantially when pre- and post-period behaviour correlate; stratified randomisation and trimming extreme values (pre-registered) also help. Or choose a more sensitive proxy metric that is validated against the real outcome.

When randomisation is impossible (a regulatory change, a price change in a whole state), use quasi-experimental methods: difference-in-differences with a comparable control group and a parallel-trends check; synthetic control for a single treated unit such as one city; regression discontinuity when treatment depends on a threshold; and interrupted time series. Each has assumptions you must state and test, and the conclusions are weaker than a clean experiment.

If you want structured, mentored practice across statistics, SQL, machine learning and cloud, Cloudsoft's APEX AI, ML, Cloud and Cyber Security program builds these skills through hands-on labs rather than slides.

Machine learning for data scientists

This section is deliberately brief and focused on what data science interviews ask. For a deeper set of algorithm, evaluation and system questions, see our machine learning interview questions guide, and if you are starting out, the AI and ML interview questions for freshers.

36. What is linear regression, what does it assume, and what are its limitations?

Answer: Linear regression models a numeric outcome as a weighted sum of predictors plus error, fitted by minimising squared error. For valid inference it assumes a linear relationship in the parameters, independent errors, constant error variance (homoscedasticity) and, for small-sample tests, roughly normal errors; strong multicollinearity makes coefficients unstable. Limitations: it cannot capture nonlinearity or interactions unless you engineer them, it is sensitive to outliers, and it is unsuitable as-is for binary or count outcomes, which need logistic or Poisson regression (generalised linear models). Its big advantage is interpretability: each coefficient is an effect holding other variables constant, though that is still association, not causation, unless the design supports it.

37. What is logistic regression, and how do you interpret its coefficients?

Answer: Logistic regression (the logit model) predicts the probability of a binary outcome by passing a linear combination of predictors through the sigmoid function. It is fitted by maximum likelihood (minimising log loss). A coefficient is the change in log-odds per unit increase in the predictor; exponentiating gives an odds ratio. It produces reasonably calibrated probabilities out of the box when well specified, trains fast, and is a strong baseline for churn, default and conversion problems. Add regularisation when you have many features, and remember that the 0.5 threshold is a default, not a business decision.

38. How does a decision tree work, and how do bagging and boosting improve on it?

Answer: A decision tree recursively splits data on the feature and threshold that most reduce impurity (Gini or entropy for classification, variance for regression), producing an interpretable set of rules that handles numeric and categorical data and nonlinearity. Single trees overfit easily and are unstable.

Ensembles fix this. Bagging trains many trees on bootstrap samples and averages them, reducing variance; random forests add random feature selection at each split to decorrelate trees. Boosting trains shallow trees sequentially, each correcting the errors of the ensemble so far, mainly reducing bias; gradient boosting libraries such as XGBoost, LightGBM and CatBoost are often the strongest choice on tabular data. Boosting needs more careful tuning and early stopping to avoid overfitting.

39. Explain the bias-variance trade-off and how regularisation helps.

Answer: Bias is error from overly simple assumptions, causing underfitting; variance is error from sensitivity to the particular training sample, causing overfitting. Expected prediction error decomposes into bias squared, variance and irreducible noise. Increasing model complexity usually lowers bias and raises variance. Regularisation adds a penalty on model complexity: L2 (ridge) shrinks coefficients smoothly, L1 (lasso) can drive some to exactly zero and acts as feature selection, and elastic net combines them. For trees, limiting depth, minimum leaf size and learning rate play the same role. Learning curves of training versus validation error show which side of the trade-off you are on.

40. What is cross-validation, and how do you avoid data leakage when you use it?

Answer: Cross-validation estimates how a model generalises to independent data by training on some folds and validating on the held-out fold, rotating through all folds. K-fold is standard; stratified k-fold keeps class balance; group k-fold keeps all rows of one customer in the same fold; time-series split always validates on data later than the training data.

Leakage sources to check: preprocessing fitted on all data; duplicate or near-duplicate entities across folds; random splits on time-ordered data; features that encode the outcome (a "closed reason" column in a churn model). Keep a final untouched test set for the last check, and tune hyperparameters only on validation folds.

41. Why is Naive Bayes called "naive", and when is it still useful?

Answer: Naive Bayes applies Bayes' theorem to classify, combining a class prior with the likelihood of the features given the class. It is "naive" because it assumes features are conditionally independent given the class, which is rarely true (words in a sentence are not independent). Despite that, it often ranks classes well, trains in one pass, works with small data and many sparse features, and remains a fast baseline for text classification such as spam or ticket routing. Its probability estimates tend to be poorly calibrated because correlated evidence gets counted multiple times, so calibrate it if you need probabilities rather than rankings.

42. How do recommender systems work? Explain collaborative filtering.

Answer: Recommenders predict which items a user is likely to engage with. Content-based methods recommend items similar to ones the user liked, using item attributes. Collaborative filtering uses the interaction matrix only: user-based (users who behave like you liked this), item-based (people who bought this also bought that) or matrix factorisation, which learns latent vectors for users and items whose dot product approximates preference. Modern systems often combine a retrieval stage (embeddings and approximate nearest-neighbour search) with a ranking model. Interview follow-ups to prepare for: cold start for new users and items, popularity bias, implicit feedback (views and purchases rather than ratings), and evaluating offline with ranking metrics such as recall at k or NDCG, then confirming online with an A/B test.

43. What are eigenvalues and eigenvectors, and how does PCA use them?

Answer: For a square matrix A, an eigenvector v is a non-zero vector whose direction does not change under the transformation: A v = ฮป v, where the eigenvalue ฮป is the scaling factor. PCA computes the eigenvectors of the data's covariance matrix (in practice usually via singular value decomposition of the centred data). The eigenvectors are the principal components, orthogonal directions of maximum variance; each eigenvalue is the variance captured along its component. Keeping the top components reduces dimensionality while retaining most variance. Standardise features first, or the variables with the largest units dominate. Components are linear combinations and harder to explain to stakeholders than the original features.

44. Which evaluation metrics would you use for an imbalanced classification problem?

Answer: Accuracy is misleading when positives are rare: predicting "no fraud" for everything looks accurate and is useless. Use precision (of the flagged cases, how many are real), recall (of the real cases, how many we caught) and their trade-off across thresholds. PR-AUC is more informative than ROC-AUC when positives are rare, because ROC-AUC can look strong while precision at practical thresholds is poor. Then translate to business terms: with a fixed investigation team, precision at the top k alerts per day is often the metric that matters. Check calibration if the scores are used as probabilities, and evaluate across segments for fairness; our bias and fairness testing guide covers how to do that systematically.

GenAI in data science work

45. How do you use LLMs in day-to-day analysis, and what are the caveats?

Answer: LLMs are useful assistants for writing and explaining pandas or SQL, drafting regex and parsing code, summarising long documents, generating hypotheses to check, and turning analysis into a first-draft narrative. The rule I follow: the LLM proposes, the data decides. Concretely:

  • Run the generated code and check its output against a number you can verify independently.
  • Watch for invented column names, wrong join keys, silently dropped rows and confident but incorrect statistical claims; LLMs can produce plausible text that is wrong (see why LLMs hallucinate).
  • Never ask an LLM to compute statistics "in its head" from pasted numbers; have it write code that you execute.
  • Do not paste customer or confidential data into tools your organisation has not approved.

Interview tip: Interviewers increasingly ask how you use these tools. A balanced answer with a concrete verification habit scores far better than either "I never use them" or "it writes all my code".

46. What is text-to-SQL, and how would you make it safe and accurate for business users?

Answer: Text-to-SQL uses an LLM to translate a natural-language question into a SQL query against your schema, runs it and returns the result. The hard parts are not generating syntax; they are business semantics and safety.

question
  -> retrieve relevant tables, columns,
     metric definitions, example queries
  -> LLM drafts SQL
  -> validate: parse, allowlist, dry run
  -> execute with read-only role + limits
  -> show result AND the SQL to the user
  • Context: give the model a curated semantic layer (what "active customer" and "net revenue" mean), not the raw schema of hundreds of tables.
  • Safety: a read-only database role, row-level security matching the user's access, statement allowlists, row and cost limits, and timeouts.
  • Accuracy: build an evaluation set of questions with verified answers and compare result sets (execution accuracy), not SQL text. Track failures by type: wrong table, wrong filter, wrong grain.
  • Trust: always show the generated SQL and the definition used, so analysts can audit it.

Our text-to-SQL agent project walkthrough builds this end to end.

47. Would you use an LLM to classify or extract information from thousands of text records? How would you evaluate it?

Answer: Often yes, for tasks like tagging support tickets by reason, extracting fields from free-text claim notes or scoring survey comments, especially when there is little labelled data. But treat it like any other model:

  1. Hand-label a representative sample (a few hundred records, stratified across categories) as a gold set.
  2. Use a fixed prompt version, a constrained label set and structured outputs so responses parse reliably (see function calling and structured outputs).
  3. Measure precision and recall per class against the gold set, and compare with a cheap baseline such as TF-IDF plus logistic regression.
  4. Estimate cost and latency for the full volume, and re-check a fresh sample periodically, because model or data changes can shift results.

Report the downstream statistic (say, share of tickets about delivery delays) with its uncertainty, including the classifier's error rate. Our LLM evaluation guide goes deeper on building evaluation sets.

48. A business team has been pasting customer spreadsheets into a public chatbot to "get insights". What do you do?

Answer: Stop the practice quickly and calmly, then give them a better path, because the underlying need is real. Personal data of customers in India is covered by the Digital Personal Data Protection Act, and sending it to an unapproved external service can breach company policy, contracts and the law.

What I would check:

  1. What data was shared, with which tool, under what account and terms, and whether it included personal or confidential fields.
  2. Escalate to the data protection or security team according to the company's incident process; do not investigate alone.
  3. What questions the team was trying to answer.
  4. Whether an approved, enterprise-governed LLM environment or a governed analytics tool exists.

Production consideration: Offer an approved route: an enterprise LLM deployment with data-handling commitments, masked or aggregated datasets, and a short guide on what can be shared. Our DPDP Act guide for AI applications explains the obligations involved.

Communicating insights

49. How do you present an analysis to a non-technical stakeholder?

Answer: Lead with the answer and the recommended action, then the evidence, then the caveats. One structure that works: "We should do X, because Y changed by Z, which we are fairly confident about because of how we measured it; the main risk is W." Use the stakeholder's metrics and vocabulary, one chart per point with the conclusion in the title, and translate uncertainty into ranges and scenarios ("between a small loss and a moderate gain") rather than p-values. Keep methodology in an appendix for those who ask. End with what decision you need and by when.

50. A result is statistically significant but the effect is tiny, and the product manager wants to announce a win. How do you handle it?

Answer: Separate statistical significance from practical significance. With a large sample, very small effects become significant. I would show the effect size with its confidence interval, translate it into business units (orders, revenue, support contacts per month), and compare it with the cost of maintaining the change and with the minimum effect we agreed was worth shipping. If it falls below that bar, the honest summary is "a real but small effect; not worth the added complexity" or "ship because it is cheap and harmless". Agreeing the minimum detectable effect and decision rule before the test makes this conversation much easier, which is the main lesson to share.

Product and business case questions

51. How would you measure the success of a new feature, such as one-click reorder in a grocery app?

Answer: Start from the goal: make repeat purchases easier, so customers order more often and stay longer. Then define metrics in layers:

  • Adoption: share of eligible users who use reorder; repeat usage.
  • Primary outcome: orders per active customer per week or repeat purchase rate.
  • Guardrails: average order value (reorder might shrink baskets if users skip browsing), cancellations and refunds, app performance.
  • Long-term: retention over several weeks.

Measure it with an A/B test at the user level if possible. Mention trade-offs explicitly; the interviewer is looking for the guardrail you thought of that others miss.

52. How would you choose a north star metric for a food delivery or quick-commerce business?

Answer: A north star metric should reflect the value customers receive and correlate with long-term revenue, while being something teams can influence. Candidates: orders delivered on time per week, weekly ordering customers, or gross merchandise value. GMV is easy to inflate with discounts; raw orders ignore delivery quality. "Weekly orders delivered successfully and on time" captures both customer value and operational quality. I would pair it with input metrics each team owns (app conversion, rider availability, restaurant acceptance rate, delivery time) and counter-metrics (contribution margin per order, cancellation rate) so no team optimises the north star at the business's expense.

53. An insurer asks you to build a churn model. How do you frame it before writing any code?

Answer: Consider an insurer whose retention team wants to know which motor policyholders will not renew. Framing questions come first:

  • Definition: is churn non-renewal at expiry, mid-term cancellation, or both? Over what window?
  • Action: what will the team do with a prediction (a call, a discount, a better quote)? How many customers can they contact per week?
  • Timing: how far before renewal must the score be available for the action to work? Only features known at that point may be used.
  • Value: the goal is retaining customers who would otherwise leave and who respond to the action, which points towards uplift modelling or at least an experiment on the outreach.
  • Fairness and regulation: pricing-related actions in insurance face regulatory scrutiny; check which features are permitted.

Success is measured by retained premium from a controlled outreach test, not AUC.

54. Leadership wants to know whether a festive-season discount campaign "worked". How do you answer?

Answer: First define "worked": incremental profit, not total sales during the campaign, because festive periods lift sales anyway. Compare with the right counterfactual: a holdout group that did not receive the discount, if one exists; otherwise a comparable prior period adjusted for trend, or difference-in-differences against regions or segments not targeted. Account for pull-forward (customers who would have bought anyway, just earlier) by checking the weeks after the campaign, cannibalisation of full-price sales, and discount cost. Present incremental orders and margin with an uncertainty range, and recommend running a proper holdout next season.

Real-world scenarios

55. A key dashboard metric dropped sharply overnight. How do you investigate?

Answer: Assume a data problem until proven otherwise, then look for a real change, and segment to localise it.

What I would check:

  1. Is the data complete? Pipeline delays, failed jobs, late-arriving events, a time zone boundary.
  2. Did a definition, tracking event or app release change? Check deploy and release logs.
  3. Is it real elsewhere? Compare against an independent source (payments versus app events).
  4. Segment: platform, app version, city, channel, new versus returning users. A drop confined to one Android version points to a bug; a drop everywhere points to something external or upstream.
  5. External causes: a public holiday, an outage at a payment provider, a competitor promotion, weather.
  6. Decompose the metric (users ร— sessions per user ร— conversion) to see which component moved.

Production consideration: Communicate early with what you know and do not know, and add data freshness and volume checks so the next pipeline failure triggers an alert before a business user notices.

56. An A/B test shows a surprisingly large lift on your primary metric. What do you do before celebrating?

Answer: Unusually large effects are more often bugs than breakthroughs, so I try to break the result before reporting it.

What I would check:

  1. Sample ratio mismatch between arms.
  2. Whether the test was stopped early after peeking, or whether this is one of many metrics or segments examined.
  3. Logging differences: does the variant fire the conversion event more often (double counting)?
  4. Outliers: is the lift driven by a few very large orders or bot traffic?
  5. Novelty: plot the daily effect; does it decay?
  6. Consistency: do related metrics move in a coherent direction?

Production consideration: If it survives, consider a replication or a holdback group after launch to confirm the effect persists.

57. A fintech app's product head asks for monthly cohort retention. Write the query and explain the pitfalls.

Answer: Define the cohort as the month of each user's first activity, then count active users in each subsequent month:

WITH firsts AS (
  SELECT user_id,
         DATE_TRUNC('month', MIN(event_date))
           AS cohort
  FROM events
  GROUP BY user_id
),
activity AS (
  SELECT DISTINCT e.user_id, f.cohort,
         DATE_TRUNC('month', e.event_date)
           AS active_month
  FROM events e
  JOIN firsts f ON f.user_id = e.user_id
)
SELECT cohort,
       (EXTRACT(YEAR FROM AGE(active_month, cohort))
          * 12
        + EXTRACT(MONTH FROM AGE(active_month, cohort)))
         AS month_number,
       COUNT(DISTINCT user_id) AS active_users
FROM activity
GROUP BY 1, 2
ORDER BY 1, 2;

This is PostgreSQL syntax; divide each row by the month-zero count for the cohort to get the retention rate.

What I would check:

  1. What counts as "active": any login, or a meaningful action such as a transaction? Logins inflate retention.
  2. Whether the events table has full history; truncated history mislabels old users as new.
  3. Test accounts, employees and duplicate user IDs across devices.
  4. The latest cohorts are incomplete; do not compare them with mature ones.

Production consideration: Put the "active" definition in a shared metrics layer so product, finance and marketing see the same retention number.

58. A hospital readmission model scored well offline but performs poorly after deployment. How do you diagnose it?

Answer: Consider a hospital group that predicts readmission within a month of discharge so care coordinators can follow up. A gap between offline and live performance usually means leakage, a training-serving mismatch or drift.

What I would check:

  1. Leakage: did training use features recorded after discharge, such as final billing codes entered days later?
  2. Training-serving skew: are features computed the same way in production, with the same data available at prediction time?
  3. Population drift: new hospitals, changed coding practices, seasonal disease patterns.
  4. Label delay: is "poor performance" measured on a complete outcome window yet?
  5. Feedback effects: if coordinators intervene on high-risk patients and prevent readmissions, the model looks wrong precisely because it worked.
  6. Subgroup performance: has it degraded for specific wards or patient groups?

Production consideration: Use a time-based validation split that mimics deployment, log features at prediction time, and keep a small randomised holdout without intervention to measure true model performance. Operating models like this is MLOps territory; our MLOps interview questions cover monitoring and drift in depth.

59. Two teams at a retailer's Hyderabad GCC report different numbers for "monthly active customers". How do you resolve it?

Answer: This is almost always a definition problem rather than a calculation bug, and resolving it is part technical, part organisational.

What I would check:

  1. Write down each team's exact definition: which actions count, which channels (store, app, web), calendar month or rolling 30 days, time zone, treatment of returns and test accounts.
  2. Reconcile on a sample: take one month, list customers counted by one team and not the other, and classify the reasons.
  3. Check identity resolution: one customer with a loyalty card in-store and a separate app account may be counted twice.
  4. Agree a single owner and definition with the business, document it, and implement it once in a governed semantic or metrics layer that dashboards read from.

Production consideration: Keep the alternative definitions under distinct, clearly named metrics if both are genuinely useful. Data engineers usually own the layer; our AI for data engineers guide shows how that work is changing with AI tooling.

60. A bank wants to roll out a natural-language "ask the data" assistant to branch managers. As the data scientist on the team, what do you insist on?

Answer: Consider a bank that wants branch managers to ask questions such as "how many new savings accounts did my branch open last month?" without waiting for an analyst. It is a text-to-SQL system with high stakes: wrong numbers will be repeated in meetings, and data access must respect branch boundaries.

What I would check:

  1. A curated metrics layer with certified definitions; the assistant may only query those.
  2. Access control: each manager sees only their branch, enforced in the database, not in the prompt.
  3. An evaluation set of real manager questions with verified answers, run before launch and after every prompt, model or schema change.
  4. Refusal behaviour: questions outside the certified metrics should get "I can't answer that reliably" plus a route to an analyst.
  5. Transparency: show the definition and the query or filters used with every answer.
  6. Logging and review of questions and answers, with privacy controls, to find gaps.

Production consideration: Start with a small pilot group, measure answer accuracy and analyst time saved, and expand only when accuracy on the evaluation set is stable. Engineering this into a secure, observable enterprise system is the kind of work Forward Deployed Engineers do.

Key takeaways

  • Statistics answers are judged on correct interpretation: p-values, confidence intervals and power are where most candidates slip.
  • In SQL and pandas, check the grain of every table before joining; fan-out is the most common silent error.
  • Experimentation pitfalls (peeking, sample ratio mismatch, interference, multiple metrics) matter more in senior interviews than test formulas.
  • Machine learning questions for data scientists focus on framing, leakage and choosing metrics that match the business decision.
  • LLMs are useful analysis assistants only with verification habits, approved tools and governed data access; text-to-SQL needs a semantic layer and evaluation set.
  • Lead with the recommendation, quantify uncertainty in business units, and separate statistical from practical significance.
  • Case and scenario questions reward structure: define the goal, the metric, the counterfactual and the guardrails before the method.

Interview preparation checklist

  • Explain p-value, confidence interval, power and Bayes' theorem out loud, each with a worked example.
  • Write joins, conditional aggregation, ROW_NUMBER top-N, LAG and a cohort retention query from memory on a sample database.
  • Practise pandas merges with validate, groupby with transform, and handling missing values inside a scikit-learn Pipeline.
  • Design one A/B test end to end: hypothesis, unit, primary and guardrail metrics, sample size, duration, analysis plan.
  • Prepare a two-minute story for one analysis that changed a decision, including what went wrong.
  • Build a small text-to-SQL or LLM-labelling prototype and an evaluation set for it, so you can discuss GenAI with evidence.
  • Practise three product case questions with a timer: feature success, north star metric, campaign impact.
  • Review the machine learning basics: regression, trees and ensembles, bias-variance, cross-validation and imbalanced metrics.

FAQ

What skills are required for a data scientist role in 2026?

Core skills are statistics and probability, SQL, Python with pandas, experiment design, machine learning fundamentals and clear communication. Increasingly, employers also expect comfort using LLM tools for analysis with sound verification habits and awareness of data privacy.

How should I prepare for data science interview questions?

Revise statistics concepts until you can explain them in plain language, practise SQL and pandas daily on real datasets, design a few A/B tests on paper, and rehearse product case questions aloud. Back it all with one or two portfolio projects you can explain in depth.

Is SQL important for data science interviews?

Yes. Most data science interview loops include a SQL round covering joins, aggregation and window functions, because pulling correct data is the foundation of every analysis. Accuracy on edge cases such as NULLs and duplicate keys matters as much as syntax.

How much statistics do I need for a data science interview?

You need solid fundamentals: distributions, sampling, hypothesis testing, p-values, confidence intervals, power, Bayes' theorem and regression. Interviewers care more about correct interpretation and knowing when assumptions break than about deriving formulas.

What is a data science case study interview?

It is an open-ended business problem, such as measuring a feature or diagnosing a metric drop, that tests how you structure the problem, choose metrics, reason about causality and communicate a recommendation. There is rarely one right answer; structure and trade-offs are what get evaluated.

Can a fresher get a data scientist job?

Yes, though many freshers start in data analyst or junior data scientist roles. Strong SQL, statistics and Python, plus projects that show end-to-end thinking from question to recommendation, make a fresher profile credible.

Do data scientists need to know GenAI and LLMs now?

Increasingly, yes. Interviews may ask how you use LLMs for coding and analysis, how you would evaluate LLM-based text classification, or how text-to-SQL systems should be governed. You do not need to train LLMs, but you should know their limitations.

What is the difference between a data scientist and a data engineer?

A data engineer builds and maintains the pipelines, warehouses and data quality that analysis depends on. A data scientist uses that data for inference, experimentation and modelling to support decisions. The roles collaborate closely and skills overlap, especially in SQL.

Is data science a good career in India?

Data science remains a strong career path in India, with demand across GCCs, product companies, banks, insurers, retailers and services firms. It suits people who enjoy statistics, programming and business problem-solving together.

Ready to prepare with mentored labs instead of reading alone? Explore Cloudsoft's APEX program for AI, ML and cloud skills, which covers the statistics, Python and machine learning foundations behind these questions. If you lean towards pipelines and data platforms, the HORIZON Data Engineering and AI program is the closer fit, and if you want to take AI systems into real enterprise environments, FDE PRO, the AI Forward Deployed Engineer program includes placement support until you're placed. Classes run in Ameerpet, beside the Metro station, or live online; call +91 96660 19191 to book a free demo.

New ยท AI Career Guide

Meet Aanya โ€” ask anything about courses, fees & placement

Instant answers from verified Cloudsoft info โ€” courses, fees, formats, placement support and free demos. Available 24/7, right here on the site.

How Aanya works โ†’
Share๐•infโœ‰
EnrollWhatsAppCall us